XML C# Book

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



Jack
Smith


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