Reputation: 2943
I have xml data that I want to locate a specific Node/Attribute (not sure the appropriate definition here) and then from there select its child node's attributes.
<Random>
<RandomChild ID="1" Name="First" />
</Random>
<Parent>
<Child ID="1" Name="First" />
<Child ID="2" Name="Second"/>
<Child ID="3" Name="Third"/>
<Child ID="4" Name="Fourth"/>
<Child ID="5" Name="Fifth"/>
<Child ID="6" Name="Sixth"/>
<Child ID="7" Name="Seventh"/>
<Child ID="8" Name="Eighth"/>
<Child ID="9" Name="Ninth"/>
</Parent>
<Random2>
<RandomChild2 ID="1" Name="First" />
</Random2>
I want the stuff within 'Parent'. The attribute names in use (ID & Name) occur in other places in this xml, so I thought the most efficient thing to do would be locate the 'Parent' node, and then select its children's nodes attributes (if there is a more efficient manner to approach this let me know).
I have tried a variety of query's but they've all failed to initialize. I'm not trying to debug a specific query, but more hoping for some clarification on how to achieve what I'm after. I've read a dozen or so similar questions on here, but they all seem to be examples with answers specific to a unique situation, and I can't figure out what I imagine is a relatively simple process.
Upvotes: 1
Views: 2063
Reputation: 167436
XDocument doc = XDocument.Load("input.xml");
foreach (XElement child in doc.Descendants("Parent").Elements("Child"))
{
Console.WriteLine("Id: {1}, Name: {2}", child.Attribute("ID").Value, child.Attribute("Name").Value);
}
Upvotes: 1