Recursive function for an xml file (hierarchial data)

只愿长相守 提交于 2019-12-24 11:35:42

问题


I have an XML file in the following format:

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

Can anyone please give me some direction on how I might traverse the file using C#?


回答1:


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.



来源:https://stackoverflow.com/questions/47026/recursive-function-for-an-xml-file-hierarchial-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!