无法将对象XText强制转换为XElement

时间:2014-09-11 14:24:48

标签: c# linq-to-xml

我有点卡住了,目前在foreach循环的第二次运行开始时在异常'ex'中遇到错误。

为什么会发生这种情况,我做错了什么?

{"Unable to cast object of type 'System.Xml.Linq.XText' to type 'System.Xml.Linq.XElement'."}   System.Exception {System.InvalidCastException}'

我的代码:

        public static void LoadMyThing()
    {
        string configfp = @"\ConfigFiles\config.xml";
        string basefp = @"\ConfigFiles\";
        try
        {
            List<string> xmlNodes = new List<string>();

            XDocument Xdoc = XDocument.Load(configfp);
            XElement XmlLst = Xdoc.Element("mylistener");

            foreach (XElement node in XmlLst.Element("parent").DescendantNodes())
            {
                thingy = (basefp + node.Value);
                Thingylist.Add(thing);
            }
        }
        catch(Exception ex)
        {
            WriteErrorLog("Thingy Loading error " + ex.ToString());
        }
    }

它要求的XML:

    <?xml version="1.0" encoding="utf-8"?>
<mylistener>
  <config>
    <mailuser>b@c.com</mailuser>
    <mailpass>H</mailpass>
    <mailip>190</mailip>
    <mailport>2</mailport>
    <recipient>m</recipient>
  </config>
  <parent>
    <b>\RFC16</b>
    <b>\RFC122</b>
    <b>\RF1</b>
    <b>\RF32</b>
    <b>\R33</b>
    <b>\RFCIB</b>
  </parent>
</mylistener>

1 个答案:

答案 0 :(得分:1)

很难确定没有看到你的XML,但如果parent节点有非XElement后代,那么我希望看到这个。例如

<parent>
    <some node /> 
    some text
</parent>

您需要知道如何处理这种情况,但避免异常的一种方法是迭代XNode而不是XElements

foreach (XNode node in XmlLst.Element("parent").DescendantNodes())
{
    if (node is XElement)
    {
        thingy = (basefp + ((XElement)node).Value);
        Thingylist.Add(mibbler);
    }
    else
    {
        // do something else
    }
}
相关问题