使用递归函数遍历XML

时间:2009-10-20 17:34:27

标签: c# xml recursion traversal

如何使用c#中的递归函数遍历(按顺序读取所有节点)XML文档?

我想要的是读取xml中的所有节点(具有属性)并以与xml相同的结构打印它们(但没有Node Localname)

由于

3 个答案:

答案 0 :(得分:25)

using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main( string[] args )
        {
            var doc = new XmlDocument();
            // Load xml document.
            TraverseNodes( doc.ChildNodes );
        }

        private static void TraverseNodes( XmlNodeList nodes )
        {
            foreach( XmlNode node in nodes )
            {
                // Do something with the node.
                TraverseNodes( node.ChildNodes );
            }
        }
    }
}

答案 1 :(得分:3)

IEnumerable<atype> yourfunction(XElement element)
{
    foreach(var node in element.Nodes)
   {
      yield return yourfunction(node);
   }

//do some stuff
}

答案 2 :(得分:1)

Here's a good example

static void Main(string[] args)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("../../Employees.xml");
    XmlNode root = doc.SelectSingleNode("*"); 
    ReadXML(root);
}

private static void ReadXML(XmlNode root)
{
    if (root is XmlElement)
    {
        DoWork(root);

        if (root.HasChildNodes)
            ReadXML(root.FirstChild);
        if (root.NextSibling != null)
            ReadXML(root.NextSibling);
    }
    else if (root is XmlText)
    {}
    else if (root is XmlComment)
    {}
}

private static void DoWork(XmlNode node)
{
    if (node.Attributes["Code"] != null)
        if(node.Name == "project" && node.Attributes["Code"].Value == "Orlando")
            Console.WriteLine(node.ParentNode.ParentNode.Attributes["Name"].Value);
}