嵌套的循环XML元素

本文关键字:元素 XML 循环 嵌套 | 更新日期: 2023-09-27 18:28:10

这是我的XML:

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

我试图通过对每个Step分别使用该Step的Check元素来循环遍历XML元素。因此:

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())
   {

然而,它没有正确循环。上面的嵌套循环结构为每个步骤的所有Check元素做一些事情,而不是只为每个步骤中的子Check元素做些事情。例如,我的代码输出为:

A1
A2
A3
B1
B2
B3

如何修复循环?

嵌套的循环XML元素

您的代码很好。查看此

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
相关文章: