XML News from Thursday, June 25, 2009

Oracle has released the final version of Java Specification Request (JSR) 225, XQuery API for Java™ (XQJ). There's also a reference implementation and technical compatibility kit. As JDBC is to SQL, XQJ is to XQuery.

The following sample Java code is meant to convey a first look and feel of the style and usage of the XQJ API. It is by no means exhaustive or complete; e.g., no error handling is shown and it is assumed that xqds is an XQDataSource object representing a given data source. It illustrates the basic steps that an application would perform to execute an XQuery expression at a given XQuery implementation.

// establish a connection to the XQuery engine 
XQConnection conn = xqds.getConnection(); 
 
// create an expression object that is later used 
// to execute an XQuery expression 
XQExpression expr = conn.createExpression(); 
 
// the XQuery expression to be executed 
String es = "for $n in fn:doc('catalog.xml')//item " + 
  "return fn:data($n/name)"; 
 
// execute the XQuery expression 
XQResultSequence result = expr.executeQuery(es); 
 
// process the result (sequence) iteratively  
while (result.next()) {  
  // retrieve the current item of the sequence as a String 
  String str  = result.getAtomicValue(); 
  System.out.println("Product name: " + str); 
} 
 
// free all resources allocated for the result 
result.close(); 
 
// free all resources allocated for the expression 
expr.close(); 
 
// free all resources allocated for the connection 
conn.close(); 

On a side note, kudos to the spec authors for putting this simple example in the spec right up front. Something like this would help a lot of other JSRs.