Home >>XQuery Tutorial >XQuery Syntax

XQuery Syntax

XQuery Syntax

XQuery elements, attributes and variables must be XML names that are true, which must obey case sensitivity.

XQuery Syntax Rules

  • XQuery measures case-sensitivity.
  • XQuery components, attributes, and variables must be XML names which are valid.
  • The value of an XQuery string may be in single or double quotes.
  • For example:, a variable XQuery is described with a $followed by a name. $bookstore
  • XQuery comments are bounded by (: and:), e.g. (XQuery Comment :)


Let's take an XML file 'books.xml' having the following data:

<book category="food">  
<title lang="en">Apple</title>  
<book category="children">  
<title lang="en">Ajay</title>  
<book category="programming">  
<title lang="en">Let's C</title>  

XQuery Conditional Expressions

he "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>  

How to run

To read the books.xqy, build a Java-based XQuery executor application, transfer it over to the XQuery expression processor, and execute the message. After that it displays the result.


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("courses.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 XQuery6 on your desktop.

Use console compile XQueryTester.java. You require JDK 1.5 or later to be enabled on your computer, and optimized classpaths.


javac XQueryTester.java


java XQueryTester