Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata