Home >>XQuery Tutorial >XQuery Syntax
XQuery elements, attributes and variables must be XML names that are true, which must obey case sensitivity.
XQuery Syntax Rules
Let's take an XML file 'books.xml' having the following data:
bookstore>
<book category="food">
<title lang="en">Apple</title>
<author>Aman</author>
<year>2016</year>
<price>150</price>
</book>
<book category="children">
<title lang="en">Ajay</title>
<author>Akira</author>
<year>2018</year>
<price>750</price>
</book>
<book category="programming">
<title lang="en">Let's C</title>
<author>Mayank</author>
<year>2006</year>
<price>450</price>
</book>
</bookstore>
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>
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.
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 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.
Compile:
javac XQueryTester.java
Execute:
java XQueryTester