Reputation: 5409
This is my XML:
<Scenario>
<Steps>
<Step Name="A">
<Check Name="1" />
<Check Name="2" />
</Step>
<Step Name="B">
<Check Name="3" />
</Step>
</Steps>
</Scenario>
I am trying to loop through the XML elements by, for each Step, doing something with that Step's respective Check elements. So:
foreach(Step step in Steps) {
foreach(Check in step) {
// Do something
}
}
It might output something like:
A1
A2
B3
The code I'm using is:
foreach (XElement step in document.Descendants("Step"))
{
// Start looping through that step's checks
foreach (XElement substep in step.Elements())
{
However it is not looping properly. The nested loop structure above is doing something for all the Check elements for each Step, instead of just doing something for the child Check elements of each Step. For example, the output of my code is:
A1
A2
A3
B1
B2
B3
How can I fix my loops?
Upvotes: 0
Views: 2514
Reputation: 35353
Your code is fine. See this
foreach (XElement step in document.Descendants("Step"))
{
// Start looping through that step's checks
foreach (XElement substep in step.Elements())
{
Console.WriteLine(step.Attribute("Name").Value + ""
+ substep.Attribute("Name").Value);
}
}
Output:
A1
A2
B3
Upvotes: 1