Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

17.3. Querying the Contents of an XML Document

Problem

You have a large and complex XML document and you need to find various pieces of information, such as all the information contained within a specific element and having a particular attribute setting. You want to query the XML structure without having to iterate through all the nodes in the XML document and searching for a particular item by hand.

Solution

In order to query a database, you normally would use SQL. In order to query an XML document, you would use XPath. In .NET, this means using the System.Xml.XPath namespace and classes like XPathDocument, XPathNavigator, and XPathNodeIterator.

In the following example, we use these classes to select nodes from an XML document we construct holding members from the board game “Clue” (or “Cluedo”, as it is known abroad) and their various roles. We want to be able to select the married female participants who were witnesses to the crime. In order to do this, we pass an XPath expression to query the XML data set as follows:

public static void QueryXML( ) { string xmlFragment = "<?xml version='1.0'?>" + "<Clue>" + "<Participant type='Perpetrator'>Professor Plum</Participant>" + "<Participant type='Witness'>Colonel Mustard</Participant>" + "<Participant type='Witness'>Mrs. White</Participant>" + "<Participant type='Witness'>Mrs. Peacock</Participant>" + "<Participant type='Witness'>Mr. Green</Participant>" + "</Clue>"; XmlTextReader reader = new XmlTextReader(xmlFragment, XmlNodeType.Element,null); ...
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# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata