Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

XPath and XPathNodeIterator

XPathNavigator provides XPath support through the Select method. It takes an XPath statement as a parameter and returns a collection of nodes in the form of the XPathNodeIterator class. XPathNodeIterator implements the methods shown here to enumerator all matching nodes:

  • Count
  • Current
  • CurrentPosition
  • MoveNext

A special feature of XPathNavigator is the ability to return a simple scalar value from an XPath statement that returns a simple value suing the Evaluate method. You pass in an XPath statement that returns a value, and it compiles the statement, evaluates it, and returns a result. You are responsible for casting the result to the appropriate type.

Listing 4 is a code demo that shows you how to take advantage of the XPath functionality. It takes an XPath statement that returns all the LineItem elements in the purchase order documents and passes that as a parameter to the Select statement of XPathNavigator to get an XPathNodeIterator. It uses the MoveNext method of XPathNodeIterator and the Current property to get XPathNavigator with its cursor set to the current node in the node set. Another highlight in the demo is the use of the GetAttribute method of XPathNavigator to gather the attribute value from an element node. After the navigation code is done, we show how the Evaluate method is used to return a simple scalar from an XPath query. The example uses an XPath query to get the sum of the number of items in the purchase order. Take a look at Listing 5 to see the results.

Listing 4: XPath Demo

using System;
using System.Xml;
using System.Xml.XPath;

namespace XmlDotNet
{

public class XPathSelectDemo
{
   public static void Main()
   {
     // load the PO
     XPathDocument doc = new XPathDocument("PO.xml");

     // retrieve the navigator
     XPathNavigator nav = doc.CreateNavigator();
        
     // select all the LineItem elements
     Console.WriteLine("Items over $300");
     XPathNodeIterator nodes = 
        nav.Select("//LineItem[@Price > 300]");
        
     // move through each node in the result set
     // and display the current node
     while (nodes.MoveNext())
     {
        XPathNavigator node = nodes.Current;   
          
        Console.WriteLine("Name:{0} Price:{1}",
          node.GetAttribute("Name",""),
          node.GetAttribute("Price",""));
     }

     // use Evaluate to get the total number of items in the
     // order
     double Total = (double) 
        nav.Evaluate("sum(//LineItem/@Qty)");
     
     Console.WriteLine();
     Console.WriteLine("Number of Items: {0}",Total);
     
   }

}
}

Listing 5: XPath Demo Results

Items over $300
Name:Computer Desk Price:499.99
Name:Computer Price:999.99

Number of Items: 4
  • + Share This
  • 🔖 Save To Your Account