XPath and XpathNodeIterator
Dale Michalk
It's a sure bet that Windows developers will be dealing with Microsoft's .NET initiative for a long time to come, which means you have to get your ducks in a row about .NET pretty quickly. This tip, excerpted from InformIT, is a follow-on to our last Windows developer tip; it discusses the relationship of function XpathNavigator and the XpathNodeIterator class.
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 enumerate 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 using the Evaluate method. You pass 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
Requires Free Membership to View
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.
Hannah Smalltree, Editorial DirectorListing 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
To read the rest of the article from which this tip is excerpted, click over to InformIT. You have to register there, but registration is free.
This was first published in July 2002