Home >>XQuery Tutorial >XQuery If Then Else Statement

XQuery If Then Else Statement

XQuery If Then Else Statement

The statement XQuery If Then Else is used to check the validity of the values that pass the input.

if (condition) then  

XQuery If Then Else Example

Let's take an example to illustrate the usage of if-then-else in XQuery sentences. Take an XML file called books.xml and add XQuery expression to it that includes an if-then-else function to retrieve the names of certain books where the price is greater than 100.

XML statementM books.xml

<?xml version="1.0" encoding="UTF-8"?>  
   <book category="JAVA">  
      <title lang="en">Learn Java </title>  
   <book category="DOTNET">  
      <title lang="en">.net</title>  
      <author>sumit verma</author>  
   <book category="XML">  
      <title lang="en">Learn XQuery </title>  
   <book category="XML">  
      <title lang="en">Learn XPath in 1 month</title>  
      <author>sujit Kumar</author>  

Xquery expression books.xqy:

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

Create a Java based XQuery executor program to read the books.xqy,

passes it to the XQuery expression processor, and executes the expression. After that the result will be displayed.


import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.InputStream;  
import javax.xml.xquery.XQConnection;  
import javax.xml.xquery.XQDataSource;  
import javax.xml.xquery.XQException;  
import javax.xml.xquery.XQPreparedExpression;  
import javax.xml.xquery.XQResultSequence;  
import com.saxonica.xqj.SaxonXQDataSource;  
public class XQueryTester {  
   public static void main(String[] args){  
      try {  
      catch (FileNotFoundException e) {  
      catch (XQException e) {  
   private static void execute() throws FileNotFoundException, XQException{  
      InputStream inputStream = new FileInputStream(new File("books.xqy"));  
      XQDataSource ds = new SaxonXQDataSource();  
      XQConnection conn = ds.getConnection();  
      XQPreparedExpression exp = conn.prepareExpression(inputStream);  
      XQResultSequence result = exp.executeQuery();  
       while (result.next()) {  

Execute XQuery against XML

Put the three files above to the same location. We put them in a folder called XQuery9 on your desktop. Use terminal compile XQueryTester.java. You require JDK 1.5 or later to be enabled on your computer, and optimized classpaths.

javac XQueryTester.java
java XQueryTester