308333 How to: Use Visual C # .NET to query XML (from mkba) via XPath expression

xiaoxiao2021-03-06  74

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

Require how to use XPath expressions to query XML troubleshooting 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 terminology creates and reads XML file XPath syntax

Back to top

How to query XML with XPath expression

Built 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 located in the following folder: program files / microsoft.net / frameworksdk / samples / quickstart / howto / samples / XML / TransformXML / VB must copy this file to / Bin / debug Folder, this folder is located in the folder you created in it. Make sure the item references the System.xml namespace. Using the USING statement on XML and XPath namespace, this will not be required in the code to limit the declarations in these namespaces. The USING statement must be used before all other statements, as shown below: USING SYSTEM.XML;

USING SYSTEM.XML.XPATH; 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; 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"); create XPathnavigator from a 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 (); 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.

STREXPIRESSION = "SUM (/ bookstore / book / price) Div count (/ bookstore / book / price"; calculates 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); 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/book/title[../price 40.00]"; create XPathNodeEiterator to select the node selected by 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); uses the selected node using the XPathNodeEiterator returned from the SELECT method of xpathnavigator. 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);

}; Use the Readline method to add PAUSE at the end of the console to display the above results more easily. // PAUSE

Console.readLine (); Build 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"); the 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:

To resolve this exception, do one of the following: Correct invalid processing instructions. Below is an example of the effective handling instruction: - or - an example below is a valid processing instruction: Remove the XML processing instruction from the books.xml file.

Back to top

Refer to the following files to download 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 XPathNodeIterator class (XPathNodeIterator class) http: // msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlXPathXPathNodeIteratorClassTopic.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 x Path 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 Union Will (W3C) Web site:

XML Path Language (XPATH) 1.0: W3C proposed in November 16, 1999 http://www.w3.org/tr/1999/rec-xpath-19991116

Back to top

The information in this article applies to:

Microsoft ADO.NET (provided with .NET Frame) Microsoft Visual C # .NET (2002) Received: 2004-8-13 (1.2) Keywords: kbdownload kbhowto kbhowtomaster KB308333

转载请注明原文地址:https://www.9cbs.com/read-108965.html

New Post(0)