共用方式為


使用 XPathNavigator 評估 XPath 運算式

XPathNavigator 類別提供 Evaluate 方法,以評估 XPath 運算式。 Evaluate 方法會使用 XPath 運算式,評估它並根據 XPath 運算式的結果傳回 W3C XPath 型別:Boolean、Number、String 或 Node Set。

評估方法

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 方法與僅將 XPathExpression 物件做為參數的 Evaluate 方法相同,只是它允許節點集引數來指定要執行評估的目前內容。 此內容對於 XPath position() 及 last() 函式是必要的,因為它們相對於目前的內容節點。 除非是用做位置步驟中的述詞,否則 position() 及 last() 函式需要節點集的參考以進行評估,否則 position 及 last 函式會傳回 0。

請參閱

參考

XmlDocument

XPathDocument

XPathNavigator

概念

使用 XPath 資料模型處理 XML 資料

使用 XPathNavigator 選取 XML 資料

使用 XPathNavigator 比對節點

在 XPath 查詢中辨識的節點型別

XPath 查詢及命名空間

編譯 XPath 運算式