本文示範如何使用 XPathNavigator 類通過 XML 路徑語言 (XPath) 運算式查詢 XPathDocument 對象。XPath 用於以編程方式計算運算式並選擇文檔中的特定節點。
回到頂端
要求
下面的列表列出了推薦使用的硬體、軟體、網路基礎結構以及所需的服務包:
本文假定您熟悉下列主題:
- XML 術語
- 建立和讀取 XML 檔案
- XPath 文法
回到頂端
如何用 XPath 運算式查詢 XML
- 在 Visual Studio .NET 中建立一個 Visual C# .NET 控制台應用程式。
備忘:本樣本使用名為 Books.xml 的檔案。您可以建立自己的 Books.xml 檔案,也可以使用 .NET 軟體開發套件 (SDK) 快速入門中包括的樣本。如果您沒有安裝"快速入門"而且也不想安裝它們,請參閱 Books.xml 下載位置的"參考"部分。如果已經安裝了"快速入門",則該檔案位於以下檔案夾中:Program Files\Microsoft.NET\FrameworkSDK\Samples\Quickstart\Howto\Samples\Xml\Transformxml\VB
必須將該檔案複製到 \Bin\Debug 檔案夾,該檔案夾位於您在其中建立該項目的檔案夾中。
- 確保該項目引用 System.Xml 名稱空間。
- 在 Xml 和 XPath 名稱空間上使用 using 語句,這樣以後就不需要在代碼中限定這些名稱空間中的聲明了。using 語句必須在所有其他聲明之前使用,如下所示:
using System.Xml;using System.Xml.XPath;
- 聲明合適的變數。聲明 XPathDocument 對象以儲存 XML 文檔,聲明 XpathNavigator 對象以計算 XPath 運算式,聲明 XPathNodeIterator 對象以迭代通過選定節點。聲明 String 對象以儲存 XPath 運算式。在 Class1 的 Main 函數中添加聲明代碼。
XPathNavigator nav; XPathDocument docNav; XPathNodeIterator NodeIter;String strExpression;
- 用樣本檔案 Books.xml 載入 XPathDocument。XPathDocument 類使用可延伸樣式表語言轉換 (XSLT) 為 XML 文檔處理提供快速和面向效能的緩衝。它類似於 XML 文件物件模型 (DOM),但經過了高度最佳化,以用於 XSLT 處理和 XPath 資料模型。
// Open the XML.docNav = new XPathDocument(@"c:\books.xml");
- 從文檔建立 XPathNavigator。XPathNavigator 對象用於進行唯讀 XPath 查詢。XPath 查詢可返回結果值或許多節點。
// Create a navigator to query with XPath.nav = docNav.CreateNavigator();
- 建立 XPath 運算式以尋找圖書的平均價格。這個 XPath 運算式返回單個值。有關 XPath 文法的完整詳細資料,請參見"參考"部分中的"XPath 文法"。
// Find the average cost of a book.// This expression uses standard XPath syntax.strExpression = "sum(/bookstore/book/price) div count(/bookstore/book/price)";
- 使用 XPathNavigator 對象的 Evaluate 方法計算 XPath 運算式。Evaluate 方法返回該運算式的結果。
// Use the Evaluate method to return the evaluated expression.Console.WriteLine("The average cost of the books are {0}", nav.Evaluate(strExpression));
- 建立 XPath 運算式以尋找價格超過 10 美元的所有圖書。這個 XPath 運算式只從 XML 摘要中返回 Title 節點。
// Find the title of the books that are greater then $10.00.strExpression = "/bookstore/book/title[../price>10.00]";
- 為使用 XPathNavigator 的 Select 方法選擇的節點建立 XPathNodeIterator。XPathNodeIterator 表示 XPath-節點集,因此它支援針對該節點集執行的操作。
// Select the node and place the results in an iterator.NodeIter = nav.Select(strExpression);
- 使用從 XPathNavigator 的 Select 方法返回的 XPathNodeIterator 遍曆選定的節點。在這種情況下,可使用 XPathNodeIterator 的 MoveNext 方法迭代通過選定的所有節點。
Console.WriteLine("List of expensive books:");//Iterate through the results showing the element value.while (NodeIter.MoveNext()) {Console.WriteLine("Book Title:{0}", NodeIter.Current.Value); };
- 使用 ReadLine 方法在控制台顯示的末尾添加 pause,以便更容易地顯示上述結果。
//PauseConsole.ReadLine();
- 產生並運行您的項目。請注意,這些結果顯示在控制台視窗中。
回到頂端