XQuery Tutorial on XQuery If Then Else

xquery provides a very useful if-then-else construct to check the validity of the input values passed. given below is the syntax of the if-then-else construct.

syntax

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

example

we will use the following books.xml file and apply to it xquery expression containing an if-then-else construct to retrieve the titles of those books with a price value that is greater than 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>

the following xquery expression is to be applied on the above xml document.

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>

output

<result>
   <title lang="en">learn .net in 24 hours</title>
   <title lang="en">learn xquery in 24 hours</title>
</result>

verify the result

to verify the result, replace the contents of books.xqy (given in the environment setup chapter) with the above xquery expression and execute the xquerytester java program.