Home >>XQuery Tutorial >XQuery FLWOR



FLWOR is an acronym for "For, Let, Where, Order Through, Return."

  • For - Collection of a list of nodes is used.
  • Let - Used for binding a sequence to a string.
  • Where - For filtering the nodes.
  • Order by - Used for grouping the nodes.
  • Return - Specifies when to return (gets checked once per each node).

XQuery FLWOR Example

Let's take an XML document that has the details regarding course selection. We are going to use a FLWOR expression to retrieve the titles of those courses which are over 30 fees.


<?xml version="1.0" encoding="UTF-8"?>
   <book category="JAVA">
      <title lang="en">Learn Java in 24 Hours</title>
   <book category="DOTNET">
      <title lang="en">Learn .Net in 24 hours</title>
   <book category="XML">
      <title lang="en">Learn XQuery in 24 hours</title>
   <book category="XML">
      <title lang="en">Learn XPath in 24 hours</title>

The accompanying document in Xquery includes the query statement to be performed on the XML document above.


let $books := (doc("books.xml")/books/book)
return <results>
   for $x in $books
   where $x/price>30
   order by $x/price
   return $x/title


<title lang="en">Learn XQuery in 24 hours</title>

<title lang="en">Learn .Net in 24 hours</title>

To read the courses.xqy, build a Java-based XQuery executor program, transfer it to the XQuery Expression Processor, and execute the term. After that it shows 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 placed them in a folder called XQuery3 on your desktop. Use the Console, build XQueryTester.java. You need JDK 1.5 or later built on your computer, and optimized classpaths.


javac XQueryTester.java


java XQueryTester