9

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

Justin R.
  • 23,435
  • 23
  • 108
  • 157
Kaja
  • 97
  • 1
  • 2
  • 9
  • 1
    I still don't understand what you really want to do. Can you maybe show a very simple and short example? What does your original XML look like, what do you want back? What do you mean by "print them" - write to the console? Write to a file? And shouldn't you be looking at XSLT for converting from XML to XML? Seems like a perfect fit. – marc_s Oct 20 '09 at 18:26
  • I agree XSLT is the best 1..but here i expected a simple recursive algo..thnx anyway – Kaja Oct 25 '09 at 15:57

3 Answers3

33
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 );
            }
        }
    }
}
Josh Close
  • 22,935
  • 13
  • 92
  • 140
4
IEnumerable<atype> yourfunction(XElement element)
{
    foreach(var node in element.Nodes)
   {
      yield return yourfunction(node);
   }

//do some stuff
}
Gregoire
  • 24,219
  • 6
  • 46
  • 73
  • i think my question in not giving enough explanation.What i want is, want to read all the nodes in xml(which has attributes) and print it in the same structure as xml(but without Node Localname) – Kaja Oct 20 '09 at 18:06
  • the return prevents the loop from, er, looping. – bmm6o Mar 13 '10 at 00:03
  • @bmm6o : have a look at the "yield return" instruction : http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx – Seb Mar 15 '10 at 13:39
  • @Seb: it my fault, I had forgotten the yield before :) – Gregoire Mar 15 '10 at 16:02
2

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);
}
Ghasem
  • 14,455
  • 21
  • 138
  • 171