Evaluate XPath Expressions using XPathNavigator

The XPathNavigator class provides the Evaluate method to evaluate an XPath expression. The Evaluate method takes an XPath expression, evaluates it and returns a W3C XPath type of Boolean, Number, String, or Node Set based on the result of the XPath expression.

The Evaluate Method

The Evaluate method takes an XPath expression, evaluates it, and returns a typed result of Boolean (Boolean), Number (Double), String (String), or Node Set (XPathNodeIterator). For example, the Evaluate method could be used in a mathematical method. The following example code calculates the total price of all the books in the books.xml file.

Dim document As XPathDocument = New XPathDocument("books.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
Dim query As XPathExpression = navigator.Compile("sum(//price/text())")  
Dim total As Double = CType(navigator.Evaluate(query), Double)  
XPathDocument document = new XPathDocument("books.xml");  
XPathNavigator navigator = document.CreateNavigator();  
XPathExpression query = navigator.Compile("sum(//price/text())");  
Double total = (Double)navigator.Evaluate(query);  

The example takes the books.xml file as input.

<?xml version="1.0" encoding="utf-8" ?> 
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>

position and last Functions

The Evaluate method is overloaded. One of the Evaluate methods takes an XPathNodeIterator object as a parameter. This particular Evaluate method is identical to the Evaluate method that takes only an XPathExpression object as a parameter, except that it allows a node set argument to specify the current context to perform the evaluation on. This context is required for the XPath position() and last() functions as they are relative to the current context node. Unless used as a predicate in a location step, the position() and last() functions require a reference to a node set in order to be evaluated otherwise, the position and last functions return 0.

See also