Iterating through nested XML nodes
I've read related questions on this but I feel I'm not grokking it. If I have an XML document with many nodes and subsequent child nodes, how do I loop through the document if I don't know how deep the child nodes go?
Here is some horrible code to demo what I mean:
foreach (var 开发者_JAVA百科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++;
}
}
}
}
Here I've only catered for when there is one nested level ("if......Count > 0"). I know there is a better way to cater for nested levels but I can't see it.
For this you have to create one recursive function, that will call it self untill the nested xml loop are not over ...
here is an example...
PLease fix if any mistake is ther...
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);
}
}
}
What you are looking for is either recursion, or a while loop where you reassign a variable which you use inside your loop constantly.
Using recursion is probably easiest, take a look at Bhavik Goyal answer, it seems to be your solution.
精彩评论