Traverse a XML using Recursive function

2019-01-11 11:54发布

How can I traverse (read all the nodes in order) a XML document using recursive functions in c#?

What I want is to read all the nodes in xml (which has attributes) and print them in the same structure as xml (but without Node Localname)

Thanks

3条回答
时光不老,我们不散
2楼-- · 2019-01-11 12:15
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 );
            }
        }
    }
}
查看更多
叼着烟拽天下
3楼-- · 2019-01-11 12:25
IEnumerable<atype> yourfunction(XElement element)
{
    foreach(var node in element.Nodes)
   {
      yield return yourfunction(node);
   }

//do some stuff
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-11 12:35

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);
}
查看更多
登录 后发表回答