views:

686

answers:

2

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

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

//do some stuff
}
Gregoire
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
the return prevents the loop from, er, looping.
Brian
@bmm6o : have a look at the "yield return" instruction : http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
Seb
@Seb: it my fault, I had forgotten the yield before :)
Gregoire
@bmm6o : oops...
Seb
+2  A: 
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
thanx..this solved the prob
Kaja
If this solved your problem, can you mark it as the correct answer? Thanks.
Josh Close