XQuery - 如果然後否則



XQuery 提供了一個非常實用的 if-then-else 結構,用來檢查傳入的輸入值的有效性。以下是 if-then-else 結構的語法。

語法

if (condition) then
 ... 
else
 ... 

示例

我們將使用以下 books.xml 檔案,並對它應用包含 if-then-else 結構的 XQuery 表示式,以檢索價格值大於 30 的那些書的標題。

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 表示式將應用於上述 XML 文件。

books.xqy

<result>
{
   if(not(doc("books.xml"))) then (
      <error>
         <message>books.xml does not exist</message>
      </error>
   )
   else ( 
      for $x in doc("books.xml")/books/book	
      where $x/price>30
      return $x/title
   )
}
</result>

輸出

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

驗證結果

要驗證結果,請將 環境設定 章節中給出的 books.xqy 的內容替換為上述 XQuery 表示式,然後執行 XQueryTester java 程式。

廣告
© . All rights reserved.