tags:

views:

2010

answers:

1

Hi,

I want to recursively traverse an XML file, and need a little help with the C# code.

My XML file looks like:

<categories>
  <category id="1">
  </category>
  <category id="2">
       <category id="3"> 
       </category>
       <category id="4"> 
              <category id="5"> 
              </category> 
       </category>
  </category>
</categories>

(sorry the angle brackets had to be replaced) : Fixed

Can someone help with the C# function that will traverse the XML file?

+2  A: 

First off, System.XML provides some excellent ways to work with XML.

I'm assuming you loaded your XML into an XMLDocument, doing so allows you to use XPath Selectors, or just walk through the DOM.

Something like this would walk from whatever element back up to the top using recursion:

public XmlNode WalkToTopNode (XmlNode CurrentNode)
{
    if (CurrentNode.ParentNode == null)
     return CurrentNode;
    else
     return WalkToTopNode(CurrentNode.ParentNode);
}

Using recursion to find a node by ID could be done somewhat like this (Note, I typed this in the textbox, it may be wrong):

public XmlNode GetElementById (string id, XmlNode node)
{
    if (node.Attributes["id"] != null && node.Attributes["id"].InnerText == id)
    { 
     return node;
    }
    else
    {
     foreach (XmlNode childNode in node.Children)
     {
      return GetElementById(id, childNode);
     }
    }

    return null;    
}

However, if you are using recursion when there are so many better node traversal ways built in to System.XML, then perhaps its time to rethink your strategy.

FlySwat