40

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.

jball
  • 24,791
  • 9
  • 70
  • 92
Night Walker
  • 20,638
  • 52
  • 151
  • 228

5 Answers5

61

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}
Incognito
  • 16,567
  • 9
  • 52
  • 74
  • 3
    Prefer this because it treats the start/end elements and content as a single item, compared to using XmlReader – Savage Nov 14 '16 at 12:27
  • not sure why foreach (XmlNode node in nodes) only loop thru 1 top node such as ("some_node") and does not get to nested children node below it and etc ... in the (XmlNodeList nodes). Can you please help? – Dung Jan 10 '21 at 15:08
43

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 = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

The result of the above will be

parent
child
nested
child
other

A list of all the elements in the XML document.

Chris Taylor
  • 52,623
  • 10
  • 78
  • 89
21

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
14

To iterate through all elements

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}
tcb
  • 4,408
  • 5
  • 34
  • 51
  • 1
    prefer using this over `XmlDocument`. See: http://stackoverflow.com/questions/1542073/xdocument-or-xmldocument (even older than this question here) – Martin Schneider Nov 18 '16 at 15:14
4

A recursive algorithm that parses through an XmlDocument

Here is an example - Recursively reading an xml document and using regex to get contents

Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html

Community
  • 1
  • 1
Alex
  • 34,899
  • 5
  • 77
  • 90