XPath和XSL轉換—-用XPath運算式查詢XML

來源:互聯網
上載者:User
如何使用 XPath 運算式查詢 XML

此樣本闡釋如何使用提供給 XPathNavigator 類的 W3C XML 路徑語言 (XPath) 運算式查詢 XPathDocument。XPathNavigator 類僅用於對文檔進行唯讀 XPath 查詢,而對於可延伸樣式表語言轉換 (XSLT) 處理,則由 XslTransform 類實現。對於 XSLT,不需要建立 XPathNavigator。

注意:XPath 是 W3C 的通用查詢語言規範,用於對 XML 文檔的某些部分進行定址。XPath 的 .NET 架構實現符合 WWW 聯合會 (W3C) XML 路徑語言 (XPath) 1.0 版規範。

要使用 XSLT 對 XML 文檔進行快速和高效的處理,請使用 XPathDocument 類。可以認為 XPathDocument 類與 XML DOM 相似,但前者為 XSLT 處理及 XPath 資料模型進行了高度最佳化。然而,與 W3C XML DOM 類不同的是,XPathDocument 類不維護節點標識,也不執行 DOM 類所要求的所有規則和驗證檢查。

您也可以針對 XmlDocument 或 XmlDataDocument 類執行 XPath 查詢。如果您使用這兩個類中的一個,則需要使用 XmlNode 類的 SelectNodes 和 SelectSingleNode 方法。

 

VB QueryXmlDocumentXPath.aspx

[運行樣本] | [查看原始碼]

此樣本載入一個包含樣本檔案 books.xml 的 XPathDocument。然後,該樣本將 XPath 運算式傳遞給 XPathQuery 函數。要傳遞的第一個 XPath 運算式選擇從根節點開始的所有書籍元素節點的所有價格節點。第二個 XPath 運算式擷取從根節點開始的、與最後的書籍元素節點關聯的 ISBN 屬性節點的文本。

要選擇與給定 XPath 運算式匹配的節點,XPathQuery 函數使用 XPathNavigator 的 Select 方法。然後,該函數建立一個 XPathNodeIterator,並使用此迭代程式重複定位某個節點並把該節點顯示在螢幕上。

注意:因為 XPathNodeIterator 表示一個 XPath-節點集,所以 XPathNodeIterator 支援在此節點集上的操作。


private const String localURL = "http://localhost/quickstart/howto/samples/Xml/QueryXmlDocumentXPath/cs/books.xml";            public static void Main()            {            QueryXmlDocumentXPathSample myQueryXmlDocumentXPathSample = new QueryXmlDocumentXPathSample();            myQueryXmlDocumentXPathSample.Run(localURL);            }            public void Run(String args)            {            Console.WriteLine("XPath Test started ...");            XPathDocument myXPathDocument = new XPathDocument(args);            XPathNavigator myXPathNavigator = myXPathDocument.CreateNavigator();            // Get all the book prices            XPathQuery(myXPathNavigator, "descendant::book/price");            // Get the ISBN of the last book            XPathQuery(myXPathNavigator, "bookstore/book[3]/@ISBN");            }            private void XPathQuery(XPathNavigator myXPathNavigator, String xpathexpr )            {            try            {            Console.WriteLine("XPath query: " + xpathexpr);            // Create a node interator to select nodes and move through them (read-only)            XPathNodeIterator myXPathNodeIterator =  myXPathNavigator.Select (xpathexpr);            while (myXPathNodeIterator.MoveNext())            {            Console.WriteLine("<" + myXPathNodeIterator.Current.Name + "> " + myXPathNodeIterator.Current.Value);            }            Console.WriteLine();            }            catch (Exception e)            {            Console.WriteLine ("Exception: {0}", e.ToString());            }            }            
private const localURL as String = "http://localhost/quickstart/howto/samples/Xml/QueryXmlDocumentXPath/cs/books.xml"            Shared sub Main            Dim myQueryXmlDocumentXPathSample as QueryXmlDocumentXPathSample            myQueryXmlDocumentXPathSample = new QueryXmlDocumentXPathSample()            myQueryXmlDocumentXPathSample.Run(localURL)            end sub            public sub Run(args as String)            Console.WriteLine("XPath Test started ...")            Dim myXPathDocument as XPathDocument = new XPathDocument(args)            Dim myXPathNavigator as XPathNavigator = myXPathDocument.CreateNavigator()            ' Get all the book prices            XPathQuery(myXPathNavigator, "descendant::book/price")            ' Get the ISBN of the last book            XPathQuery(myXPathNavigator, "bookstore/book[3]/@ISBN")            end sub            private sub XPathQuery(myXPathNavigator as XPathNavigator, xpathexpr as String )            try            Console.WriteLine("XPath query: " + xpathexpr)            ' Create a node interator to select nodes and move through them (read-only)            Dim myXPathNodeIterator as XPathNodeIterator  =  myXPathNavigator.Select (xpathexpr)            while (myXPathNodeIterator.MoveNext())            Console.WriteLine("<" & myXPathNodeIterator.Current.Name + "> " & myXPathNodeIterator.Current.Value)            end while            Console.WriteLine()            catch e as Exception            Console.WriteLine ("Exception: {0}", e.ToString())            end try            end sub            
C# VB  

第一個查詢選擇從根節點開始的所有書籍的“價格”節點。第二個查詢擷取從根節點開始的最後的書籍元素節點的“ISBN”屬性文本。

也可使用 XPathExpression 類執行查詢。使用 XPathExpression 類而不使用 Select 方法(在 XPathNavigator 上)中的字串運算式的原因主要有兩個:
1) 運算式只編譯一次,並可重複使用多次,這樣可提高效能
2) 可使用 XmlNamespaceManager 類將 XPath 運算式中使用的首碼綁定到某個命名空間,這樣當選擇一組節點時,就允許使用帶首碼的 XPath 運算式。
下列代碼顯示一般用法,即選擇其 ISBN 屬性在 urn:samples 命名空間中的所有書籍。

// compile the expression            XPathExpression expr = nav.Compile("book/@mybk:ISBN");            // set namespace(s) used in the expression            XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable());            mngr.AddNamespace("mybk","urn:samples");            expr.SetContext(mngr);            // select the nodes            XPathNodeIterator myXPathNodeIterator = nav.Select(expr);            
' compile the expression            Dim expr as XPathExpression = nav.Compile("book/@mybk:ISBN")            ' set namespace(s) used in the expression            Dim mngr as XmlNamespaceManager = new XmlNamespaceManager(new NameTable())            mngr.AddNamespace("mybk","urn:samples")            expr.SetContext(mngr)            ' select the nodes            Dim myXPathNodeIterator as XPathNodeIterator = nav.Select(expr)            
C# VB  

如果 XPathExpression 沒有首碼,則假設該命名空間 URI 為空白的命名空間。如果 XML 包括預設的命名空間,則必須仍然使用 SetContext 方法,並提供一個包含首碼和命名空間 URI 的 XmlNamespaceManager,以處理預設命名空間。有關使用 XmlNamespaceManager 的更多資訊,請參閱“XmlNameSpace 管理器與命名表”主題。

摘要
  1. 要查詢 XPathDocument、XmlDataDocument 或 XmlDocument,可以為 XPathNavigator 類提供 XPath 運算式。
  2. XPathNavigator 類僅用於對 XML 文檔進行唯讀 XPath 查詢。
  3. XPathDocument 類為使用 XSLT 處理 XML 文檔提供快速、高效的特定緩衝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.