Reputation: 1037
I have an unfortunate issue where the names of the root element and descendant element are the same, the second one has more descendents with info. Example below:
<dispatchnames>
<dispatchnames>
<first>mike</first>
<last>allison</last>
</dispatchnames>
<dispatchnames>
<first>jeff</first>
<last>ellington</last>
</dispatchnames>
</dispatchnames>
I am attempting to code in C#, this is my current code for XML without the same name:
XDocument xdoc = XDocument.Parse(xmlString);
IEnumerable<TrackData> data = from info in xdoc.Descendants("dispatchnames")
select new TrackData(
info.Element("first").Value,
info.Element("last").Value);
How should I handle it?
Upvotes: 1
Views: 244
Reputation: 5659
Add a where
clause to verify that that element isn't the root element. If that element isn't actually the root, check info.Element("first") != null
instead
XDocument xdoc = XDocument.Parse(xmlString);
IEnumerable<TrackData> data = from info in xdoc.Descendants("dispatchnames")
where xdoc.Root != info
select new TrackData(
info.Element("first").Value,
info.Element("last").Value);
Also, note that the XML you posted isn't well-formed. I tested this with XML structured as follows:
<dispatchnames>
<dispatchnames>
<first>mike</first>
<last>allison</last>
</dispatchnames>
<dispatchnames>
<first>jeff</first>
<last>ellington</last>
</dispatchnames>
</dispatchnames>
Upvotes: 1