XQuery - XPath



XQuery 相容 XPath。它使用 XPath 表示式來限制 XML 集合的搜尋結果。有關如何使用 XPath 的更多詳細資訊,請檢視我們的 XPath 教程

回想一下我們之前用來獲取書籍列表的以下 XPath 表示式。

doc("books.xml")/books/book

XPath 示例

我們將使用 books.xml 檔案並對其應用 XQuery。

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
   
   <book category="JAVA">
      <title lang="en">Learn Java in 24 Hours</title>
      <author>Robert</author>
      <year>2005</year>
      <price>30.00</price>
   </book>
   
   <book category="DOTNET">
      <title lang="en">Learn .Net in 24 hours</title>
      <author>Peter</author>
      <year>2011</year>
      <price>40.50</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XQuery in 24 hours</title>
      <author>Robert</author>
      <author>Peter</author> 
      <year>2013</year>
      <price>50.00</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XPath in 24 hours</title>
      <author>Jay Ban</author>
      <year>2010</year>
      <price>16.50</price>
   </book>
   
</books>

我們在此提供了 XQuery 語句的三個版本,它們實現了同一目標:顯示價格值大於 30 的書籍標題。

XQuery – 版本 1

(: read the entire xml document :)
let $books := doc("books.xml")

for $x in $books/books/book
where $x/price > 30
return $x/title

輸出

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

XQuery – 版本 2

(: read all books :)
let $books := doc("books.xml")/books/book

for $x in $books
where $x/price > 30
return $x/title

輸出

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

XQuery – 版本 3

(: read books with price > 30 :)
let $books := doc("books.xml")/books/book[price > 30]

for $x in $books
return $x/title

輸出

<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>

驗證結果

要驗證結果,請使用上面的 XQuery 表示式替換 books.xqy(在 環境設定 章節中提供)的內容,然後執行 XQueryTester java 程式。

廣告
© . All rights reserved.