Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata