Use Visual C# to query XML with an XPath expression
This article introduces how to query an XPathDocument
object with an XML Path Language (XPath) expression by using the XPathNavigator
class.
Original product version: Visual Studio, .NET Framework
Original KB number: 308333
Summary
XPath is used programmatically to evaluate expressions and select specific nodes in a document.
This article refers to the Microsoft .NET Framework Class Library namespace System.Xml.XPath
.
This article assumes that you're familiar with the following topics:
- Visual C#
- XML terminology
- Creating and reading an XML file
- XPath syntax
Query XML with an XPath expression
Create a new Visual C# Console Application in Visual Studio.
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 don't have the quickstarts installed and don't want to install them, see the References section for the Books.xml download location. If you have the quickstarts installed, the file can be found in
Program Files\Microsoft.NET\FrameworkSDK\Samples\Quickstart\Howto\Samples\Xml\Transforxml\VB
folder. You can copy the file to the\Bin\Debug
folder, which is located under the folder in which you created this project.
- 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 don't have the quickstarts installed and don't want to install them, see the References section for the Books.xml download location. If you have the quickstarts installed, the file can be found in
Make sure that the project references the
System.Xml
namespace.Use the
using
statement on theXml
andXPath
namespaces so that you aren't required to qualify declarations in those namespaces later in your code. You can use theusing
statement before 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, anXpathNavigator
object to evaluate XPath expressions, and anXPathNodeIterator
object to iterate through selected nodes. Declare aString
object to hold the XPath expressions. Add the declaration code in theMain
function inClass1
.XPathNavigator nav; XPathDocument docNav; XPathNodeIterator NodeIter; String strExpression;
Load an
XPathDocument
with the sample file Books.xml. TheXPathDocument
class uses Extensible Stylesheet Language Transformations (XSLT) to provide a fast and performance-oriented cache for XML document processing. It's similar to the XML Document Object Model (DOM) but is highly optimized for XSLT processing and theXPath
data model.// Open the XML. docNav = new XPathDocument(@"c:\books.xml");
Create an
XPathNavigator
from the document. TheXPathNavigator
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 XPath Syntax in the References section.
// Find the average cost of a book. // This expression uses standard XPath syntax. strExpression = "sum(/bookstore/book/price) div count(/bookstore/book/price)";
Use the
Evaluate
method of theXPathNavigator
object to evaluate the XPath expression. TheEvaluate
method returns the results of the expression.// Use the Evaluate method to return the evaluated expression. Console.WriteLine("The average cost of the books are {0}", nav.Evaluate(strExpression));
Create an XPath expression to find all of the books that cost more than 10 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 = "/bookstore/book/title[../price>10.00]";
Create an
XPathNodeIterator
for the nodes that are selected with theSelect
method of theXPathNavigator
. TheXPathNodeIterator
represents an XPath nodeset, and supports operations on this nodeset.// Select the node and place the results in an iterator. NodeIter = nav.Select(strExpression);
Use the
XPathNodeIterator
, which was returned from theSelect
method ofXPathNavigator
, to move through the selected nodes. In this case, you can use theMoveNext
method of theXPathNodeIterator
to iterate through all of the selected nodes.Console.WriteLine("List of expensive books:"); //Iterate through the results showing the element value. while (NodeIter.MoveNext()) { Console.WriteLine("Book Title: {0}", NodeIter.Current.Value); };
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();
Build and run your project.
Note
The results are displayed in the console window.
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("c:\\books.xml");
The exception error is caused by an invalid processing instruction. For example, the processing instruction may contain extraneous spaces. The following example is an invalid processing instruction:
<?xml version='1.0' ?>
To resolve the exception, use one of the following resolutions:
Correct the invalid processing instruction. The following example is a valid processing instruction:
<?xml version='1.0'?>
Remove the XML processing instruction from the Books.xml file.
References
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for