Looping through All Nodes in an XML Document using c# .NET

This example demonstrates an application that loops through all the nodes of an XML document and prints out the name of the element or the text contained in the element in the case of an XmlText element.

Input xml Books.xml:

<?xml version="1.0"?>
<books>
  <book>
    <title>This is title1</title>
    <author>author1</author>
    <code>1234</code>
  </book>
  <book>
    <title>This is title2</title>
    <author>author2</author>
    <code>4352</code>
  </book>
</books>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
 
namespace LoopThroughXmlDocument
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
 
    private void buttonLoopThroughDocument_Click(object sender, EventArgs e)
    {
      XmlDocument document = new XmlDocument();
 
      // A Post event (on the properties page for the project) copies the XML to the
      // output folder whenever you compile, which is why no explicit path is needed.
      document.Load("Books.xml");
      textBoxResult.Text = FormatText(document.DocumentElement as XmlNode, "", "");
    }
 
    private string FormatText(XmlNode node, string text, string indent)
    {
      if (node is XmlText)
      {
        text += node.Value;
        return text;
      }
 
      if (string.IsNullOrEmpty(indent))
        indent = "";
      else
      {
        text += "\r\n" + indent;
      }
 
      if (node is XmlComment)
      {
        text += node.OuterXml;
        return text;
      }
 
      text += "<" + node.Name;
      if (node.Attributes.Count > 0)
      {
        AddAttributes(node, ref text);
      }
      if (node.HasChildNodes)
      {
        text += ">";
        foreach (XmlNode child in node.ChildNodes)
        {
          text = FormatText(child, text, indent + "  ");
        }
        if (node.ChildNodes.Count == 1 &&
           (node.FirstChild is XmlText || node.FirstChild is XmlComment))
          text += "</" + node.Name + ">";
        else
          text += "\r\n" + indent + "</" + node.Name + ">";
      }
      else
        text += " />";
      return text;
    }
 
    private void AddAttributes(XmlNode node, ref string text)
    {
      foreach (XmlAttribute xa in node.Attributes)
      {
        text += " " + xa.Name + "='" + xa.Value + "'";
      }
    }
  }
}
Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone