Microsoft Knowledge Base Email Alertz

This article demonstrates how to query an

Search KbAlertz

Advanced Search

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]











Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks

Article ID: 301220 - Last Review: April 26, 2006 - Revision: 5.4

How to query XML with an XPath expression by using Visual Basic .NET

This article was previously published under Q301220

On This Page

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.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
  • Visual Studio .NET
This article assumes that you are familiar with the following topics:
  • XML terminology
  • Creating and reading an XML file
  • XPath syntax

How to query XML with an XPath expression

  1. Create a new Visual Basic .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 "References" 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.
  2. Make sure that the project references the System.Xml namespace.
  3. Use the Imports 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 Imports statements prior to any other declarations.
    Imports System.Xml
    Imports System.Xml.XPath
    					
  4. 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 procedure in Module1.
    Dim nav As XPathNavigator
    Dim docNav As XPathDocument
    Dim NodeIter As XPathNodeIterator
    Dim strExpression As String
    					
  5. 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("books.xml")
    					
  6. 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
    					
  7. 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)"
    					
  8. 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("The average cost of the books are {0}", nav.Evaluate(strExpression))
    					
  9. 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 than 10 dollars.
    strExpression = "http://support.microsoft.com/bookstore/book/title[../price>10.00]"
    					
  10. 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 put the results into an iterator.
    NodeIter = nav.Select(strExpression)
    					
  11. 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("List of expensive books:")
    
    'Iterate through the results that show the element value.
    While (NodeIter.MoveNext())
        Console.WriteLine("Book Title: {0}", NodeIter.Current.Value)
    End While
    					
  12. 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()
    					
  13. Build and run your project. Note that the results are displayed in the console window.

REFERENCES

The following file is available for download from the Microsoft Download Center:
Collapse this imageExpand this image
Download
Download Books.xml now (http://download.microsoft.com/download/xml/utility/1.0.0.1/wxp/en-us/books.exe)
For more information, see the following Web sites:
"XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation"
http://msdn.microsoft.com/msdnmag/issues/01/01/xml/ (http://msdn.microsoft.com/msdnmag/issues/01/01/xml/)

XPathNavigator Class
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator(VS.71).aspx (http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator(VS.71).aspx)

XPathDocument Class
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument(VS.71).aspx (http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument(VS.71).aspx)

XPathNodeIterator Class
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator(VS.71).aspx (http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator(VS.71).aspx)

"XSLT Transformations with the XslTransform"
http://msdn.microsoft.com/en-us/library/aa735784.aspx (http://msdn.microsoft.com/en-us/library/aa735784.aspx)

XPath Examples
http://msdn.microsoft.com/en-us/library/ms256086.aspx (http://msdn.microsoft.com/en-us/library/ms256086.aspx)

XPath Syntax
http://msdn.microsoft.com/en-us/library/ms256471(VS.85).aspx (http://msdn.microsoft.com/en-us/library/ms256471(VS.85).aspx)

"XML Path Language (XPath)"
Version 1.0: W3C Recommendation 16 November 1999
http://www.w3.org/TR/1999/REC-xpath-19991116 (http://www.w3.org/TR/1999/REC-xpath-19991116)

APPLIES TO
  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework Class Libraries 1.0
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbdownload kbsample kbhowtomaster KB301220
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate