Traversing an XmlDocument

To illustrate traversing an XmlDocument, we'll use the following XML file:

 

        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <customer id="123" status="archived">
          <firstname>Jack</firstname>
          <lastname>Smith</lastname>
        </customer>

  

The ChildNodes property (defined in XNode) allows you to descend into the tree structure.

This returns an indexable collection:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {

        XmlDocument doc = new XmlDocument();
        doc.Load("customer.xml");

        Console.WriteLine(doc.DocumentElement.ChildNodes[0].InnerText); 
        Console.WriteLine(doc.DocumentElement.ChildNodes[1].InnerText); 
    }
}

The output:


Jack
Smith

With the ParentNode property, you can ascend back up the tree:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("customer.xml");

        Console.WriteLine(doc.DocumentElement.ChildNodes[1].ParentNode.Name); 
    }
}

The output:


customer

The following two statements both output firstname:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("customer.xml");

        Console.WriteLine(doc.DocumentElement.FirstChild.Name);
        Console.WriteLine(doc.DocumentElement.LastChild.PreviousSibling.Name);
    }
}

The output:


firstname
firstname
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.