Microsoft KB Archive/317069

From BetaArchive Wiki

Article ID: 317069

Article Last Modified on 8/12/2005



APPLIES TO

  • Microsoft .NET Framework 1.1
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft .NET Framework 1.0



This article was previously published under Q317069

SUMMARY

This step-by-step article demonstrates how to use the classes in the System.Xml.XPath namespace to execute XPath queries in .NET applications.

back to the top

Explore the System.Xml.XPath Namespace

The System.Xml.XPath namespace contains the XPath parser and the evaluation engine of the .NET Framework. The System.Xml.XPath namespace supports the World Wide Web Consortium (W3C) XML Path Language (XPath) Version 1.0 Recommendation. For more information about the XPath recommendation, visit the following W3C Web site:

The System.Xml.XPath namespace also contains the following classes that are optimized to execute XPath queries and navigate the generated resultsets programmatically:

  • XPathDocument: A high performance, read-only cache for processing XML documents and streams. XPathDocument is optimized for Extensible Stylesheet Language Transformation (XSLT) processing and for the XPath data model. XPathDocument uses the document object model (DOM)-based parsing model (loads the source XML into an in-memory tree structure) but does not implement the interfaces required to insert, to modify, or to delete nodes in an Extensible Markup Language (XML) document or stream.
  • XPathNavigator: This class is based on the XPath data model. XPathNavigator provides the required methods for you to execute XPath queries against XML data that is loaded into an XPathDocument. XPathNavigator is instantiated by using the CreateNavigator method of an XPathDocument object. You can also use XPathNavigator to compile frequently executed XPath query expressions and generate a System.Xml.XPath.XPathExpression object that encapsulates the compiled query.
  • XPathNodeIterator: Provides a forward-only, read-only iterator. When you use the Select method of an XPathNavigator object to execute an XPath query, an instance of XPathNodeIterator is created. You can use XPathNodeIterator to navigate the resultset that is generated by the XPath query.
  • XPathExpression: Encapsulates a compiled XPath query expression. You must compile an XPath query expression before you can execute the query expression. A compiled XPath expression contains syntax that is verified to conform to the W3C XPath Query Language specification. A call to the Compile method of an XPathNavigator object returns the XPathExpression class. Typically, you use XPathExpression to supply a precompiled XPath query expression in a call to the Select method of an XPathNavigator object.
  • XPathException: The .NET Framework exception that is generated when an error occurs while processing an XPath query expression. The Select method and the Compile method of the XPathNavigator class can raise XPathException.

back to the top

Create Sample XML Documents

To create two sample XML documents to use with the subsequent .NET code sample, follow these steps:

  1. Use Notepad or a similar text editor to paste the following code in a new XML document named Books.xml. Save the document in the root folder on your hard disk.

    <?xml version='1.0'?>
    <Books>
    <Book>
      <Title>Beginning XML</Title>
      <Publisher>Wrox</Publisher>
    </Book>
    <Book>
      <Title>XML Step by Step</Title>
      <Publisher>MSPress</Publisher>
    </Book>
    <Book>
      <Title>Professional XML</Title>
      <Publisher>Wrox</Publisher>
    </Book>
    <Book>
      <Title>Developing XML solutions</Title>
      <Publisher>MSPress</Publisher>
    </Book>
    </Books>
                        
  2. Use Notepad or a similar text editor to paste the following code in a new XML document named DotNetBooks.xml. Save the document in the root folder on your hard disk.

    <?xml version='1.0'?>
    <DotNetBooks>
    <DotNetBook>
      <Title>Professional C#</Title>
      <Publisher>Wrox</Publisher>
    </DotNetBook>
    <DotNetBook>
      <Title>ADO.Net Core Reference</Title>
      <Publisher>MSPress</Publisher>
    </DotNetBook>
    <DotNetBook>
      <Title>Professional VB.Net</Title>
      <Publisher>Wrox</Publisher>
    </DotNetBook>
    <DotNetBook>
      <Title>Inside C#</Title>
      <Publisher>MSPress</Publisher>
    </DotNetBook>
    </DotNetBooks>

back to the top

Create a Visual Basic .NET Project

  1. Start Visual Studio .NET, and then create a new Visual Basic .NET Windows Application project.
  2. Drag two Button controls from the toolbox to Form1.vb.
  3. Paste the following code in the Click_Event procedure of the first command button:

    'Instantiate the XPathDocument class.
    Dim xmldoc As New System.Xml.XPath.XPathDocument("c:\books.xml")
    
    'Instantiate the XPathNavigator class.
    Dim nav As System.Xml.XPath.XPathNavigator = xmldoc.CreateNavigator()
    
    'Instantiate the XPathIterator class.
    Dim iterator As System.Xml.XPath.XPathNodeIterator = nav.Select("//Publisher[. = 'MSPress']/parent::node()/Title")
    
    'Use the XPathIterator class to navigate through the generated resultset
    'and then display the selected Titles.
    Do While iterator.MoveNext
        System.Diagnostics.Debug.WriteLine(iterator.Current.Value)
    Loop
                        
  4. Read the inline comments to understand the functionality of the code. Pay specific attention to how the code instantiates and uses object instances of each of the classes in the System.Xml.XPath namespace. Note that a string specifies the XPath query expression parameter in the call to the Select method of the XPathNavigator object.
  5. Paste the following code in the Click_Event procedure of the second command button:

    'Construct the XPathDocument by specifying the path to Books.xml.
    Dim xmldoc As New System.Xml.XPath.XPathDocument("c:\books.xml")
    
    'Create the XPathNavigator.
    Dim nav As System.Xml.XPath.XPathNavigator = xmldoc.CreateNavigator()
    
    'Compile the XPath query expression to identify all MSPress Titles.
    'The Compile method of the XPathNavigator generates an XPathExpression object
    'that encapsulates the compiled query expression.
    
    Dim expr As System.Xml.XPath.XPathExpression = nav.Compile("//Publisher[. = 'MSPress']/parent::node()/Title")
    
    'Execute the Select method of the XPathNavigator to create the XPathNodeIterator.
    'Note that the sample code supplies the XPathExpression object as the query expression parameter.
    Dim iterator As System.Xml.XPath.XPathNodeIterator = nav.Select(expr)
    
    System.Diagnostics.Debug.WriteLine("MSPress titles in books.xml...")
    System.Diagnostics.Debug.WriteLine("******************************")
    
    'Use the iterator to navigate the generated resultset.
    Do While iterator.MoveNext
        System.Diagnostics.Debug.WriteLine(iterator.Current.Value)
    Loop
    
    
    'Release the XPathDocument and XPathNavigator.
    xmldoc = Nothing
    nav = Nothing
    
    System.Diagnostics.Debug.WriteLine(vbCrLf & "MSPress titles in DotNetBooks.xml...")
    System.Diagnostics.Debug.WriteLine("******************************")
    
    'Specify the path to DotNetBooks.xml to reconstruct the XPathDocument.
    xmldoc = New System.Xml.XPath.XPathDocument("c:\DotNetBooks.xml")
    
    'Create the XPathNavigator.
    nav = xmldoc.CreateNavigator()
    
    'Reuse the XPathExpression that you compiled previously to locate
    'all MSPress titles in DotNetBooks.xml.
    
    'You can reuse the XPathExpression because the hierarchy of elements that are referenced
    'in the XPath query is the same in Books.xml and DotNetBooks.xml. 
    'For example, the Publisher element is a child of the Title element in both XML documents.
    'The hierarchy must be identical for you to reuse the same XPathExpression object
    'across different XML documents/streams.
    
    'When you use an XPathExpression object, and the Select method executes,
    'the XPath query is not recompiled. 
    
    iterator = nav.Select(expr)
    
    'Use the iterator to navigate the generated resultset.
    Do While iterator.MoveNext
         System.Diagnostics.Debug.WriteLine(iterator.Current.Value)
    Loop
                        
  6. Read the inline comments to understand the functionality of the code. Pay specific attention to how the sample code instantiates the XPathExpression object the first time (against Books.xml), and then reuses the object when the XPath query executes the second time (against DotNetBooks.xml).

back to the top

Test the Project

  1. Save the changes to the Visual Basic .NET project, and then execute the project.
  2. When the form appears, click the first command button to execute the code that uses a string to specify the XPath query expression. The output of the specified XPath query against Books.xml appears as follows:

    XML Step by Step
    Developing XML solutions
                        
  3. Click the second command button to execute the code that uses an XPathExpression object to specify the XPath query expression. The output of the specified XPath query against Books.xml and DotNetBooks.xml appears as follows:

    MSPress titles in books.xml...
    ******************************
    XML Step by Step
    Developing XML solutions
    
    MSPress titles in DotNetBooks.xml...
    ******************************
    ADO.Net Core Reference
    Inside C#
                        

back to the top

Keywords: kbhowtomaster KB317069