C# 遍历嵌套的XML节点

C# 遍历嵌套的XML节点,c#,xml,C#,Xml,我读过有关这方面的问题,但我觉得我不是在摸索。如果我有一个包含许多节点和后续子节点的XML文档,那么如果我不知道子节点有多深,如何循环遍历文档 下面是一些可怕的代码来演示我的意思: foreach (var section in xml.Sections.Keys) { cont.ContentControls.Add(new Separator(xml.Sections[section].Name)); foreach (var variable in xml.Sections

我读过有关这方面的问题,但我觉得我不是在摸索。如果我有一个包含许多节点和后续子节点的XML文档,那么如果我不知道子节点有多深,如何循环遍历文档

下面是一些可怕的代码来演示我的意思:

foreach (var section in xml.Sections.Keys)
{
    cont.ContentControls.Add(new Separator(xml.Sections[section].Name));
    foreach (var variable in xml.Sections[section].Variables)
    {
        TraverseVars(cont, xml.Sections[section].Name, variable.Value.Name, variable.Value.Title, variable.Value.Default1, variable.Value.Default2, variable.Value.Default3, variable.Value.DesignerType);
        i++;
    }
    if (xml.Sections[section].Sections.Count > 0)
    {
        foreach (var section2 in xml.Sections[section].Sections.Keys)
        {
            cont.ContentControls.Add(new Separator(xml.Sections[section].Sections[section2].Name));
            foreach (var variable2 in xml.Sections[section].Sections[section2].Variables)
            {
                TraverseVars(cont, xml.Sections[section].Name, variable2.Value.Name, variable2.Value.Title, variable2.Value.Default1, 
                            variable2.Value.Default2, variable2.Value.Default3, variable2.Value.DesignerType);
                i++;
            }
        }
    }
}

在这里,我只考虑了一个嵌套级别(“if……Count>0”)的情况。我知道有更好的方法来满足嵌套级别的需求,但我看不到。

您要寻找的是一个while循环,或者是一个while循环,您可以在循环中不断重新分配一个变量



使用递归可能是最简单的,看看Bhavik Goyal的答案,这似乎是您的解决方案。

为此,您必须创建一个递归函数,该函数将自己调用,直到嵌套的xml循环结束为止

这里有一个例子

如果有任何错误,请修复

public void xmlsection(XmlSection Section)
{
    cont.ContentControls.Add(new Separator(xml.Sections[section].Name));
    foreach (var variable in xml.Sections[section].Variables)
    {
        TraverseVars(cont, xml.Sections[section].Name, variable.Value.Name, variable.Value.Title, variable.Value.Default1, variable.Value.Default2, variable.Value.Default3, variable.Value.DesignerType);
        i++;
    }
    if (xml.Sections[section].Sections.Count > 0)
    {
        foreach (var section2 in xml.Sections[section].Sections.Keys)
        {
xmlsection(section2);
        }
    }

}

如果您希望选择一个特定的节点,无论它处于何种级别,您都可以使用带有“//nodename”的select,它将获取具有该名称的所有节点;遍历XML文档中的所有节点不要忘记将答案标记为有助于您的答案。
i++
可能不再有效,但我相信OP会找到解决该问题的方法;p@steven是的,你是对的,我并没有写完整的代码。我刚刚演示了执行递归函数的方法。