Reputation: 2107
I'm a bit stuck, currently getting a an error being caught in the exception 'ex' at the start of the second run through of the foreach loop.
Why is this happening and what am I doing wrong?
{"Unable to cast object of type 'System.Xml.Linq.XText' to type 'System.Xml.Linq.XElement'."} System.Exception {System.InvalidCastException}'
My code:
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());
}
}
The XML it's calling to:
<?xml version="1.0" encoding="utf-8"?>
<mylistener>
<config>
<mailuser>[email protected]</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>
Upvotes: 1
Views: 2808
Reputation: 28728
Hard to be sure without seeing your XML, but if the parent
node has non XElement descendants then I'd expect to see this. For example
<parent>
<some node />
some text
</parent>
You need to know how you want to handle this case, but one way to avoid an exception would be to iterate XNodes rather than 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
}
}
Upvotes: 1