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 tag; ...

Get C# in a Nutshell 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.