XQuery - If Then Else
XQuery fornisce un costrutto if-then-else molto utile per verificare la validità dei valori di input passati. Di seguito è riportata la sintassi del costrutto if-then-else.
Sintassi
if (condition) then
 ... 
else
 ... 
    Esempio
Useremo il seguente file books.xml e applicheremo ad esso un'espressione XQuery contenente un costrutto if-then-else per recuperare i titoli di quei libri con un valore di prezzo maggiore di 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> 
    La seguente espressione XQuery deve essere applicata al documento XML precedente.
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> 
    Produzione
<result>
   <title lang="en">Learn .Net in 24 hours</title>
   <title lang="en">Learn XQuery in 24 hours</title>
</result> 
    Verifica il risultato
Per verificare il risultato, sostituire il contenuto di books.xqy (fornito nel capitolo Configurazione dell'ambiente ) con l'espressione XQuery sopra ed eseguire il programma java XQueryTester.
