Searching Using XPathNavigator

Another way to query XML documents using XPath is to use the .NET XPathNavigator class, which is defined in the System.Xml.XPath namespace. This namespace contains a set of classes that provide optimized operations for searching and iterating XML data using XPath.

To demonstrate the use of these functions, we will use the same set of customer data as in the previous examples, as shown in Example 14-4.

Example 14-4. Searching an XML document using XPathNavigator

using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.XPath; namespace Programming_CSharp { public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ) { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } } // Main program public class Tester { static void Main( ) { XmlDocument customerXml = CreateCustomerXml( ); XPathNavigator nav = customerXml.CreateNavigator( ); string xPath = "descendant::Customer[@FirstName='Douglas']"; XPathNavigator navNode = nav.SelectSingleNode(xPath); Console.WriteLine("\nSelectSingleNode(\"{0}\")...", xPath); if (navNode != null) { Console.WriteLine(navNode.OuterXml); XmlElement elem = navNode.UnderlyingObject as XmlElement; if (elem != null) Console.WriteLine(elem.OuterXml); else ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.