XQuery elements, attributes, and variables must be valid XML names and follow case sensitivity.
XQuery Syntax Rules
Let's take an XML file 'books.xml' having the following data:
<bookstore> <book category="Romantic"> <title lang="en">If she loves me</title> <author>Ajeet Kumar</author> <year>2014</year> <price>150</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>700</price> </book> <book category="programming"> <title lang="en">Let's C</title> <author>Yashwant Kanetkar</author> <year>2003</year> <price>200</price> </book> </bookstore>
The "If-Then-Else" conditional statement is allowed in XQuery.
XQuery statement:
books.xqy
for $x in doc("books.xml")/bookstore/book
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else <adult>{data($x/title)}</adult>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("courses.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 XQuery6.
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:
 
There are two types for comparing values in XQuery.
Difference between general comparison and value comparison
It can be explained by an example. The following expression returns true if any q attributes have a value greater than 100.
$bookstore//book/@q > 100
The following expression returns true if there is only one q attribute returned by the expression, and its value is greater than 10. If more than one q is returned, an error occurs:
$bookstore//book/@q gt 100
