The XQuery If Then Else statement is used to check the validity of the passing input values.
if (condition) then ... else ...
Let's take an example to demonstrate the usage of if-then-else statement in XQuery. Take an XML file named books.xml and apply to it XQuery expression containing an if-then-else construct to retrieve the titles of those books where price is greater than 100.
XML statementM
books.xml
<?xml version="1.0" encoding="UTF-8"?> <books> <book category="JAVA"> <title lang="en">Learn Java Programming</title> <author>Sonoo Jaiswal</author> <year>2012</year> <price>400.00</price> </book> <book category="DOTNET"> <title lang="en">DOTNET Fun</title> <author>Balaswamy</author> <year>2008</year> <price>300.50</price> </book> <book category="XML"> <title lang="en">Learn XQuery in 1 month</title> <author>Ajeet Kumar</author> <author>Sam Lee</author> <year>2013</year> <price>250.00</price> </book> <book category="XML"> <title lang="en">Learn XPath in 1 month</title> <author>Ajeet Kumar</author> <year>2014</year> <price>150.50</price> </book> </books>
Xquery expression
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> 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. XQueryTester.java 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 { execute(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XQException e) { e.printStackTrace(); } } 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()) { System.out.println(result.getItemAsString(null)); } } }
Put the above three files to a same location. We put them on desktop in a folder name XQuery9. Compile XQueryTester.java using console. You must have JDK 1.5 or later installed on your computer and classpaths are configured.
Compile:
javac XQueryTester.java
Execute:
java XQueryTester
Output: