
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Querying the Contents of an XML Document
|
837
Solution
To query a database, you normally use SQL. To query an XML document, you cur-
rently use
XPath or with SQL Server 2005 possibly XQuery (as .NET 2.0 does not sup-
port it as part of the Base Class Library [BCL.NET]). In .NET, this means using the
System.Xml.XPath namespace and classes like XPathDocument, XPathNavigator, and
XPathNodeIterator.
In the following example, you use these classes to select nodes from an XML docu-
ment that holds members from the board game Clue (or Cluedo, as it is known
abroad) and their various roles. You want to be able to select the married female par-
ticipants who were witnesses to the crime. In order to do this, pass an
XPath expres-
sion to query the XML dataset as shown in Example 15-2.
Example 15-2. Querying an XML document
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>";
using (StringReader reader = new StringReader(xmlFragment))
{
// Instantiate an ...