Night Walker Night Walker - 1 year ago 118
C# Question

Iterating through all nodes in XML file

I want to iterate through all nodes in an XML file and print their names.
What is the best way to do this? I am using .NET 2.0.

Answer Source

I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"
        <nested />

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
    if (rdr.NodeType == XmlNodeType.Element)

The result of the above will be


A list of all the elements in the XML document.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download