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

Get C# Cookbook 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.