Next page Previous page Start of chapter End of chapter

XQuery evaluation

The package javax.xml.xquery supports the evaluation of XQuery expressions for querying XML documents. This package in under development as Java Specification Requests 225. An implementation of the API is provided by BaseX.

The following example, provided by the BaseX Team, shows how to:

  1. get an XQuery data source;
  2. connect to the XQuery data source;
  3. prepare an XQuery expression;
  4. execute the XQuery expression;
  5. iterate through the sequence resulting from the XQuery execution.
import javax.xml.xquery.XQConnection; 
import javax.xml.xquery.XQDataSource; 
import javax.xml.xquery.XQPreparedExpression; 
import javax.xml.xquery.XQResultSequence; 
 
/** 
 * This class serves an example for executing XQuery requests using the XQuery API. 
 * 
 * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License 
 * @author BaseX Team 
 */ 
public final class XQueryAPIExample { 
  /** Database Driver. */ 
  private static final String DRIVER = "org.basex.api.xqj.BXQDataSource"; 
 
   /** 
   * Main method of the example class. 
   * @param args (ignored) command-line arguments 
   * @throws Exception exception 
   */ 
  public static void main(final String[] args) throws Exception { 
    // Gets the XQDataSource for the specified Driver. 
    final XQDataSource source = (XQDataSource) Class.forName(DRIVER).newInstance(); 
    // Creates an XQConnection 
    final XQConnection conn = source.getConnection(); 
    // Prepares the Expression with the Document and the Query. 
    final XQPreparedExpression expr = conn.prepareExpression("for $p in doc('auction.xml')//person return $p/name"); 
    // Executes the XQuery query. 
    final XQResultSequence result = expr.executeQuery(); 
    // Gets all results of the execution. 
    while(result.next()) { 
      // Prints the results to the console. 
      System.out.println(result.getItemAsString(null)); 
    } 
  } 
} 

Compile with

javac -cp BaseX5-xqj.jar XQueryAPIExample.java
and run with
java -cp BaseX5.jar;BaseX5-xqj.jar;. XQueryAPIExample
Read the XQuery API specifications for more information.

Next page Previous page Start of chapter End of chapter
Caffè XML - Massimo Franceschet