類別 XPathNavigator 提供 Evaluate 評估 XPath 運算式的方法。 方法 Evaluate 會採用 XPath 運算式、評估它,並根據 XPath 表達式的結果傳回 Boolean、Number、String 或 Node Set 的 W3C XPath 類型。
Evaluate 方法
方法Evaluate會採用 XPath 運算式,評估它,並傳回型別化的結果:布林值 (Boolean)、數值 (Double)、字串 (String) 或節點集 (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>
位置和最後函數
方法 Evaluate 已被重載。 其中一個方法會 Evaluate 接受 XPathNodeIterator 物件做為參數。 這個特定 Evaluate 方法與只接受 Evaluate 物件作為參數的 XPathExpression 方法相同,差異在於它允許使用節點集參數來指定當前的上下文以執行評估。 XPath position() 和 last() 函式需要此背景,因為它們是相對於當前的上下文節點。 除非在位置步驟中作為述詞使用,position() 和 last() 函式需要節點集的參考才能進行評估;否則,position 和 last 函式會傳回 0。