XQuery Sequences

XQuery sequences are used to specify an ordered collection of items. These items can be of similar or different types.

Creating a sequence

An XQuery sequence is created using parenthesis with strings inside quotes or double quotes or numbers. XML elements can also be used as the items of a sequence.

There are two ways to create items of sequence iterated one by one.

  • Using index
  • Using values

XQuery Expression for Index

items.xqy

snippet
let $items := ('orange', <apple/>, <fruit type="juicy"/>, <vehicle type="car">sentro</vehicle>, 1,2,3,'a','b',"abc")
let $count := count($items)
return
<result>
   <count>{$count}</count>   
   <items>
      {
	     for $item in $items
         return <item>{$item}</item>
      }
   </items>   
</result>

How to run

Create a Java based XQuery executor program to read the items.xqy, passes it to the XQuery expression processor, and executes the expression. After that the result will be displayed.

XQueryTester.java

snippet
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("items.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));
      }
   }	
}

Execute XQuery against XML

Put the above three files to a same location. We put them on desktop in a folder name XQuery7. 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:

XQUERY Sequence 1

XQuery Expression for Index

items.xqy

snippet
let $items := (1,2,3,4,5,6)
let $count := count($items)
return
   <result>
      <count>{$count}</count>  
      <items>
      {
         for $item in $items
         return <item>{$item}</item>
      }
      </items>   
   </result>

Follow the same procedure as above:

Output:

XQUERY Sequence 2
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +