Microsoft KB Archive/308333

= How To Query XML with an XPath Expression by Using Visual C# .NET =

Article ID: 308333

Article Last Modified on 10/30/2007

-

APPLIES TO


 * Microsoft ADO.NET 1.0
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q308333



For a Microsoft Visual Basic .NET version of this article, see 301220.

This article refers to the following Microsoft .NET Framework Class Library namespace:
 * System.Xml.XPath

IN THIS TASK
SUMMARY
 * Requirements
 * How to Query XML with an XPath Expression
 * Troubleshooting

REFERENCES



SUMMARY
This article demonstrates how to query an XPathDocument object with an XML Path Language (XPath) expression using the XPathNavigator class. XPath is used programmatically to evaluate expressions and select specific nodes in a document.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Visual C# .NET

This article assumes that you are familiar with the following topics:
 * XML terminology
 * Creating and reading an XML file
 * XPath syntax

back to the top

How to Query XML with an XPath Expression
 Create a new Visual C# .NET Console Application in Visual Studio .NET.

NOTE: This example uses a file named Books.xml. You can create your own Books.xml file, or you can use the sample that is included with the .NET Software Development Kit (SDK) Quickstarts. If you do not have the Quickstarts installed and do not want to install them, see the &quot;References&quot; section for the Books.xml download location. If you have the Quickstarts installed, the file can be found in the following folder:

Program Files\Microsoft.NET\FrameworkSDK\Samples\Quickstart\Howto\Samples\Xml\Transformxml\VB

You must copy the file to the \Bin\Debug folder, which is located under the folder in which you created this project. Make sure that the project references the System.Xml namespace.  Use the using statement on the Xml and XPath namespaces so that you are not required to qualify declarations in those namespaces later in your code. You must use the using statement prior to any other declarations, as follows: using System.Xml; using System.Xml.XPath;   Declare the appropriate variables. Declare an XPathDocument object to hold the XML document, an XpathNavigator object to evaluate XPath expressions, and an XPathNodeIterator object to iterate through selected nodes. Declare a String object to hold the XPath expressions. Add the declaration code in the Main function in Class1. XPathNavigator nav; XPathDocument docNav; XPathNodeIterator NodeIter; String strExpression;   Load an XPathDocument with the sample file Books.xml. The XPathDocument class uses Extensible Stylesheet Language Transformations (XSLT) to provide a fast and performance-oriented cache for XML document processing. It is similar to the XML Document Object Model (DOM) but is highly optimized for XSLT processing and the XPath data model. // Open the XML. docNav = new XPathDocument(@&quot;c:\books.xml&quot;);   Create an XPathNavigator from the document. The XPathNavigator object is used for read-only XPath queries. The XPath queries may return a resulting value or many nodes. // Create a navigator to query with XPath. nav = docNav.CreateNavigator;   Create an XPath expression to find the average cost of a book. This XPath expression returns a single value. For full details on XPath syntax, see &quot;XPath Syntax&quot; in the &quot;References&quot; section. // Find the average cost of a book. // This expression uses standard XPath syntax. strExpression = &quot;sum(/bookstore/book/price) div count(/bookstore/book/price)&quot;; </li>  Use the Evaluate method of the XPathNavigator object to evaluate the XPath expression. The Evaluate method returns the results of the expression. // Use the Evaluate method to return the evaluated expression. Console.WriteLine(&quot;The average cost of the books are {0}&quot;, nav.Evaluate(strExpression)); </li>  Create an XPath expression to find all of the books that cost more than ten dollars. This XPath expression returns only Title nodes from the XML source. // Find the title of the books that are greater then $10.00. strExpression = &quot;/bookstore/book/title[../price>10.00]&quot;; </li>  Create an XPathNodeIterator for the nodes that are selected with the Select method of the XPathNavigator. The XPathNodeIterator represents an XPath nodeset and therefore supports operations on this nodeset. // Select the node and place the results in an iterator. NodeIter = nav.Select(strExpression); </li>  Use the XPathNodeIterator, which was returned from the Select method of XPathNavigator, to move through the selected nodes. In this case, you can use the MoveNext method of the XPathNodeIterator to iterate through all of the selected nodes. Console.WriteLine(&quot;List of expensive books:&quot;); //Iterate through the results showing the element value. while (NodeIter.MoveNext) {     Console.WriteLine(&quot;Book Title: {0}&quot;, NodeIter.Current.Value); };                   </li>  Use the ReadLine method to add a pause at the end of the console display to more readily display the above results. // Pause Console.ReadLine; </li> Build and run your project. Note that the results are displayed in the console window.</li></ol>

back to the top

Troubleshooting
When you test the code, you may receive the following exception error message:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.xml.dll

Additional information: System error.

The exception error occurs on the following line of code: docNav = new XPathDocument(&quot;c:\\books.xml&quot;); The exception error is caused by an invalid processing instruction. For example, the processing instruction may contain extraneous spaces. The following is an example of an invalid processing instruction: <?xml version='1.0' ?> To resolve the exception, do either of the following: <ul>  Correct the invalid processing instruction. The following is an example of a valid processing instruction: <?xml version='1.0'?> -OR- </li> Remove the XML processing instruction from the Books.xml file.</li></ul>

back to the top

<div class="references_section">