使用 XPathNavigator 计算 XPath 表达式
XPathNavigator 类提供了 Evaluate 方法来计算 XPath 表达式。 Evaluate 方法使用 XPath 表达式,计算表达式,然后基于 XPath 表达式的结果返回 Boolean、Number、String 或 Node Set 的 W3C XPath 类型。
Evaluate 方法
Evaluate 方法使用 XPath 表达式,计算表达式,然后返回 Boolean (Boolean)、Number (Double)、String (String) 或 Node Set (XPathNodeIterator) 的类型化结果。 例如,Evaluate 方法可以在数学方法中使用。 以下示例代码计算 books.xml
文件中的所有图书的总价格。
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)
Console.WriteLine(total)
XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathExpression query = navigator.Compile("sum(//price/text())");
Double total = (Double)navigator.Evaluate(query);
Console.WriteLine(total);
该示例使用 books.xml
文件作为输入。
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
position 和 last 函数
Evaluate 方法是重载方法。 一个 Evaluate 方法使用 XPathNodeIterator 对象作为参数。 此特定的 Evaluate 方法与只使用 Evaluate 对象作为参数的 XPathExpression 方法相同,只是允许使用节点集参数指定要执行计算的当前上下文。 XPath position()
和 last()
函数需要此上下文,因为这两个函数相对于当前上下文节点。 除非在定位步骤中作为谓词使用,position()
和 last()
函数要求引用节点集以便进行计算,否则,position
和 last
函数将返回 0
。