How to: Use Visual C # .NET to query XML via XPath expression
Article ID: 308333 Last Update Date: August 13, 2004 Version: 1.0
The release number of this article has been CHS308333
For Microsoft Visual Basic .NET versions of this article, see
301220.
This article references the following Microsoft .NET Framework Class Bank Name Space:
• System.xml.xpath
This task content
•summary
• Requirements • How to use XPath Expressions to query XML • Troubleshooting • Reference
This page
Summary reference
summary
This article demonstrates how to use
XPathnavigator class Inquiry via XML Path Language (XPath) expression
XpathDocument object. XPath is used to programmatically calculate expressions and select specific nodes in the document.
Back to top
Require the following list lists the recommended hardware, software, network infrastructure, and service packs required:
• Visual C # .NET This article assumes that you are familiar with the following topics:
• XML terms • Create and read XML files • XPath syntax
Back to top
How to query XML with XPath expression
1. Create a Visual C # .NET console application in Visual Studio .NET. Note: This example uses a file called Books.xml. You can create an example of your own Books.xml file or you can use the example of the .NET Software Development Kit (SDK). If you do not install "Quick Start" and don't want to install them, see the "Reference" section of the Books.xml download location. If "Quick Start" has been installed, the file is in the following folder:
Program files / microsoft.net / frameworksdk / samples / quickstart / howto / samples / xml / transformxml / vb
This file must be copied to the / bin / debug folder, which is located in the folder you created in this project. 2. Make sure the item references the System.xml namespace. 3. Use the using statement on XML and XPath names, so you don't need to limit the declarations in these namespaces in your code. The USING statement must be used before all other statements, as shown below: USING SYSTEM.XML;
Using system.xml.xpath; 4. Declare the appropriate variable. Declare the XPathDocument object to save the XML document, declare the XPathNavigator object to calculate the XPath expression, declare the XPathNodeEiterator object to iterate through the selected node. Declare the String object to save the XPath expression. Add a declaration code in the main function of Class1. Xpathnavigator NAV;
XpathDocument docnav;
XpathnodeEiterator Nodeiter;
String strexpression; 5. Load XpathDocument with sample file books.xml. The XPathDocument class uses Scalable Style Language Conversion (XSLT) to provide fast and performance cache for XML document processing. It is similar to the XML Document Object Model (DOM), but has been highly optimized for XSLT processing and XPath data models. // Open the xml.
Docnav = new xpathdocument (@ "c: /books.xml"); 6. Create Xpathnavigator from the document. Xpathnavigator objects are used to read only XPath queries. XPath queries can return a result value or a number of nodes. // Create a navigator to query with xpath.nav = docnav.createnavigator (); 7. Create an XPath expression to find average price of books. This XPath expression returns a single value. For complete details on the XPath syntax, see "XPath Syntax" in the Reference section. // Find the average cost of a book.
// this Expression Uses Standard XPath Syntax.
strexpression = "SUM (/ BookStore / Book / Price) Div Count (/ BookStore / Book / Price)"; 8. Calculate the XPath expression using the Evaluate method of the XPathnavigator object. Evaluate method Returns the result of this expression. // use the evataly method to return the evaluated expression.
Console.writeline ("The average cost of the books are {0}", nav.expression); 9. Create an XPath expression to find all books for more than $ 10. This XPath expression only returns a Title node from the XML source. // Find The Title of the Books That Are Greater TEN $ 10.00.
Strexpression = "/bookStore/book/title[/price/book/title[../price> 40.00]";10. Create XPathNodeEiterator to create XPathNodeeiterator to select the node selected using the SELECT method for XPathnavigator. XpathNodeIterator represents the XPath node set, so it supports operations performed for this node set. // Select the node and place the results in an itrator.
Nodeiter = nav.select (strexpression); 11. Use the XPathNodeEiterator returned from the SELECT method from XPathnavigator to traverse the selected node. In this case, the MOVENEXT method of the XPathNodeTeiterator can be used to iterate through all 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);
}; 12. Add PAUSE to the end of the console display using the Readline method to make it easier to display the above results. // PAUSE
Console.readline (); 13. Generate and run your project. Note that these results are displayed in the console window.
Back to top
Troubleshooting When testing 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. This exception error occurs on the following code line:
Docnav = New XPathDocument ("C: //Books.xml");
This exception error is caused by invalid processing instructions. For example, the processing instructions may contain extra spaces. Here is an example of an invalid processing instruction:
XML Version = '1.0'?>
To resolve this exception, do one of the following:
• Correct invalid processing instructions. The following is an example of the effective handling instruction: XML Version = '1.0'?> - or - • The following is an example of a valid processing instruction: Remove the XML processing instruction from the books.xml file.
Back to top
reference
The following files can be downloaded from the Microsoft Download Center:
Download Books.xml now
For more information, please visit the following Microsoft Web site:
XML: .NET Framework XML Classes and C # Offer Simple, Scalable Data Manipulation (XML: .NET Framework XML class and C # in .NET) R />
http://msdn.microsoft.com/msdnmag/issues/01/01/xml/xml.asp
XPathnavigator Class
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlXPathXPathnavigatorClasStopic.asp
XpathDocument Class (XPathDocument class)
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlXPathXPathDocumentClasstopic.asp
XPathnodeEiterator Class (XPathNodeTeiterator class)
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlXPathXPathNodeTeiteratorClasstopic.asp
XSLT Transformations with The Xsltransform Class (XSLT conversion using XSLTransform class)
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconxslttransformationswithXSLTRANSFORMCLASS.ASP
XPath Examples (XPATH Example)
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk30/htm/xmrefxpathexamples.asp
XPath Syntax (XPath Syntax)
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk30/htm/xmrefxpathysyntax.asp For more information on XPath, please visit the following WWW Federation (W3C) Web site :
XML Path Language (XPath)
1.0 Edition: W3C proposed on November 16, 1999
http://www.w3.org/TR/1999/Rec-XPath-19991116
Back to top