Export (0) Print
Expand All

Select Nodes Using XPath Navigation 

The XML Document Object Model (DOM) contains methods that allow you to use XML Path Language (XPath) navigation to query information in the DOM. You can use XPath to find a single, specific node or to find all nodes that match some criteria.

XPath Select Methods

Retrieving a node or multiple nodes in the DOM without XPath requires a lot of navigation code. XPath, however, requires one line of code. The DOM classes provide two methods for XPath selection. The SelectSingleNode method returns the first node that matches the selection criteria. The SelectNodes method returns an XmlNodeList containing the matching nodes.

The following sample example shows an XPath query returning all nodes that have a book author of Smith.

XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("descendant::book[author/last-name='Smith']");

Once a node list has been generated, the list can be looped over as shown in the following sample.

foreach (XmlNode book in nodeList)
{
    // Do something.
}

The root variable was set to the document element. Setting the starting point for the XPath query sets the context node, which is the starting point for the XPath query. The example above starts the XPath query at the document element. If you do not want to start at the document element, but want to start from the first child of the document element, you can code the select statement shown in the following example.

this doc.DocumentElement.FirstChild.SelectNodes(. . .);

All XmlNodeList objects are synchronized with the underlying document. Therefore, if you iterate through the node list and modify the value of a node, that node is also updated in the document it came from.

NoteNote

When the underlying document is modified, it is advisable to rerun the select. If the node modified is one that could cause the node to be added to the node list when it was not previously, or would now cause it to be removed from the node list, there is no guarantee that the node list is now accurate.

The following example modifies the price of a book in the node list and at the same time modifies the price of that node in the underlying document.

XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");

XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");
 
// Change the price on the books.
foreach (XmlNode book in nodeList)
{
    book.LastChild.InnerText="15.95";
}
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);

Namespaces in XPath Expressions

XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix, the prefix and namespace URI pair must be added to the XmlNamespaceManager, and the XmlNamespaceManager is passed to the SelectNodes or SelectSingleNode method.

NoteNote

If the XPath expression does not include a prefix, it is assumed that the namespace Uniform Resource Identifier (URI) is the empty namespace. If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you does not get any nodes selected.

For more information on the namespaces, see Namespaces in an XML Document.

Example

The following example displays all book titles. The XmlNamespaceManager resolves the default namespace in the XPath expression.

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

  Public Shared Sub Main()

      Dim doc As XmlDocument = New XmlDocument()
      doc.Load("newbooks.xml")

      ' Create an XmlNamespaceManager to resolve the default namespace.
      Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
      nsmgr.AddNamespace("bk", "urn:newbooks-schema")

      ' Select and display all book titles.
      Dim nodeList As XmlNodeList 
      Dim root As XmlElement = doc.DocumentElement
      nodeList = root.SelectNodes("/bk:bookstore/bk:book/bk:title", nsmgr)
      Dim title as XmlNode
      For Each title In nodeList
        Console.WriteLine(title.InnerXml)
      Next

  End Sub
End Class

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {

      XmlDocument doc = new XmlDocument();
      doc.Load("newbooks.xml");

      // Create an XmlNamespaceManager to resolve the default namespace.
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
      nsmgr.AddNamespace("bk", "urn:newbooks-schema");

      // Select and display all book titles.
      XmlNodeList nodeList;
      XmlElement root = doc.DocumentElement;
      nodeList = root.SelectNodes("/bk:bookstore/bk:book/bk:title", nsmgr);
      foreach (XmlNode title in nodeList) {
        Console.WriteLine(title.InnerXml);
      }

   }

}

Input

<?xml version='1.0'?>
<bookstore xmlns="urn:newbooks-schema">
  <book genre="novel" style="hardcover">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" style="other">
    <title>The Poisonwood Bible</title>
    <author>
      <first-name>Barbara</first-name>
      <last-name>Kingsolver</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

Output

The Handmaid's Tale

The Poisonwood Bible

See Also

Community Additions

ADD
Show:
© 2014 Microsoft