嵌套循环XML元素

时间:2013-08-19 16:59:48

标签: c# xml loops while-loop

这是我的XML:

<Scenario>
   <Steps>
      <Step Name="A">
         <Check Name="1" />
         <Check Name="2" />
      </Step>
      <Step Name="B">
         <Check Name="3" />
      </Step>
   </Steps>
</Scenario>

我正在尝试遍历XML元素,对于每个步骤,使用Step的各个Check元素执行某些操作。所以:

foreach(Step step in Steps) {
   foreach(Check in step) {
      // Do something
   }
}

它可能会输出如下内容:

A1
A2
B3

我正在使用的代码是:

foreach (XElement step in document.Descendants("Step"))
{
   // Start looping through that step's checks
   foreach (XElement substep in step.Elements())
   {

然而,它没有正确循环。上面的嵌套循环结构正在为每个Step的所有Check元素执行某些操作,而不是仅为每个Step的子Check元素执行某些操作。例如,我的代码输出是:

A1
A2
A3
B1
B2
B3

如何修复循环?

1 个答案:

答案 0 :(得分:1)

你的代码很好。见这个

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);
    }
}

输出:

A1
A2
B3