Selecting Nodes Using XPath

Walking the resulting tree of XmlNode instances that is created by XML readers can be tedious and error-prone in its own right, particularly when a specific set of nodes scattered throughout the tree is desired. To address this requirement, the W3C defined a query API called XPath for selecting nodes within an Infoset (the tree-like hierarchy a DOM-compliant parser transforms XML input into, according to the W3C Specifications) representation. In the .NET XML libraries, this is implemented by specifying the IXPathNavigable interface, with any type that supports the interface in turn supporting XPath queries against it.

Without the availability of XPath, programmers must write code like that in the following example in order to list the author names found in a given book element:

using System; using System.IO; using System.Xml; class App { public static void Main(string[ ] args) { string xmlContent = "<book>" + " <title>C# in a Nutshell</title>" + " <authors>" + " <author>Drayton</author>" + " <author>Neward</author>" + " <author>Albahari</author>" + " </authors>" + "</book>"; XmlTextReader xtr = new XmlTextReader(new StringReader(xmlContent)); XmlDocument doc = new XmlDocument( ); doc.Load(xtr); XmlNode docElement = doc.DocumentElement; // This gets us title and authors foreach (XmlNode n2 in docElement.ChildNodes) { if (n2.Name = = "authors") { // This gets us author tags foreach (XmlNode n3 in n2.ChildNodes) { // This gets us the text inside the author ...

Get C# in a Nutshell, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.