XQuery - If Then Else

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>Learn Java in 24 Hours</title>
      <author>Robert</author>
      <year>2005</year>
      <price>30.00</price>
   </book>
   
   <book category="DOTNET">
      <title>Learn .Net in 24 hours</title>
      <author>Peter</author>
      <year>2011</year>
      <price>40.50</price>
   </book>
   
   <book category="XML">
      <title>Learn XQuery in 24 hours</title>
      <author>Robert</author>
      <author>Peter</author>
      <year>2013</year>
      <price>50.00</price>
   </book>
   
   <book category="XML">
      <title>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>Learn .Net in 24 hours</title>
   <title>Learn XQuery in 24 hours</title>
</result>

验证结果

要验证结果,请替换 books.xqy (在环境设置章节中给出)使用上面的XQuery表达式并执行XQueryTester java程序.