Use Visual C #. Net to query XML through an XPATH expression

Source: Internet
Author: User
Tags xslt

This document demonstrates how to useXpathnavigatorClass query using XML Path Language (XPath) ExpressionsXpathdocumentObject. XPath is used to calculate expressions programmatically and select specific nodes in the document.

Back to Top

Requirements

The following list lists the recommended hardware, software, network infrastructure, and required service packages:

    • Visual C #. net

This document assumes that you are familiar with the following topics:

    • XML terminology
    • Create and read XML files
    • XPath syntax

Back to Top

How to use an XPATH expression to query XML
  1. Create a New Visual C #. Net console application in Visual Studio. NETProgram.
    Remarks: In this example, a file named books. XML is used. You can create your own books. xml file or use the example included in the. net sdk quick start. If you do not want to install "Quick Start" and do not want to install them, see the "Reference" section of the books. xml download location. If you have installed "Quick Start", the file is located 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 in the folder where you created the project.

  2. Make sure that this project referencesSystem. xmlNamespace.
  3. InXMLAndXpathNamespace usageUsingStatement.CodeAre declared in these namespaces.UsingThe statement must be used before all other declarations, as shown below:

    Using system. xml; using system. xml. XPath;

  4. Declare appropriate variables. StatementXpathdocumentObject To save the XML document, declareXpathnavigatorObject To calculate the XPath expression, declareXpathnodeiteratorObject To iterate through the selected node. StatementStringObject To save the XPath expression. In class1MainAdd declaration code to the function.

    Xpathnavigator nav; xpathdocument docnav; xpathnodeiterator nodeiter; string strexpression;

  5. Load with the example file books. xmlXpathdocument.XpathdocumentClass uses extensible style sheet language conversion (XSLT) to provide fast and performance-oriented caching for XML document processing. It is similar to the XML Document Object Model (DOM), but is highly optimized for XSLT processing and XPath data models.

    // Open the xml.doc nav = new xpathdocument (@ "C: \ books. xml ");

  6. Create from documentXpathnavigator.XpathnavigatorThe object is used for read-only XPath queries. XPath queries can return result values or many nodes.

    // Create a navigator to query with XPath. Nav = docnav. createnavigator ();

  7. Create an XPATH expression to find the average price of a book. This XPath expression returns a single value. For more information about the XPath syntax, see "XPath Syntax" in "Reference ".

    // Find the average cost of a book. // This expression uses standard XPath syntax. strexpression = "sum (/bookstore/book/price) Div count (/bookstore/book/price )";

  8. UseXpathnavigatorObjectEvaluateMethod to Calculate the XPath expression.EvaluateReturns the result of this expression.

    // Use the Evaluate Method to return the evaluated expression. Console. writeline ("the average cost of the books are {0}", Nav. Evaluate (strexpression ));

  9. Create an XPATH expression to search for all books that cost more than $10. This XPath expression only returns the title node from the XML source.

    // Find the title of the books that are greater then $ 10.00.strexpression = "/bookstore/book/title [../price> 10.00]";

  10. For useXpathnavigatorOfSelectMethod selected node CreationXpathnodeiterator.XpathnodeiteratorIndicates the XPath node set. Therefore, it supports operations performed on the node set.

    // Select the node and place the results in an iterator. nodeiter = nav. Select (strexpression );

  11. Use slaveXpathnavigatorOfSelectMethod returnXpathnodeiteratorTraverse selected nodes. In this case, you can useXpathnodeiteratorOfMovenextThe method iterates through all 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. UseReadlineMethod to add pause at the end of the console to display the above results more easily.

    // Pauseconsole. Readline ();

  13. Generate and run your project. Note that these results are displayed in the console window.

Back to Top

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.