Saxonica.com

Invoking XQuery using the XQJ API

XQJ (XQuery API for Java) is a proposed vendor-neutral API for invoking XQuery from Java applications. It is currently published as "Early Draft Review 2" (JSR 225) at http://jcp.org/en/jsr/detail?id=225. Saxon 8.8 includes an almost-complete implementation of this API.

For information on how to use the API, please see the JSR 225 documentation. Note that the interface is subject to (perhaps extensive) change.

Saxon's implementation of XQJ, together with the XQJ interface definitions themselves, is packaged in the JAR file saxon8-xqj.jar. Note that the XQJ interfaces have been renamed from package javax.xml.xquery to net.sf.saxon.javax.xml.xquery. This is to avoid conflicts with other versions of XQJ, since the interfaces are not yet stable.

XQJ has many similarities with JDBC, and its general style is that of a client-server API in which the application opens a "connection" to a database. This of course does not fit the Saxon in-process model particularly well; on the other hand, apart from the terminology and the use of some methods (such as the ability to set a connection timeout) that make little sense in a Saxon context, the API works equally well in an environment like Saxon where the XQuery processor is invoked directly and runs within the same Java VM as the client application.

The samples directory in the issued saxon-resources download file includes a Java test application, XQJExamples.java, which illustrates some of the possible ways of invoking Saxon using the XQJ interface.

Note that Saxon will generally only recognize its own implementation of XQJ interfaces. For example, the interface XQDynamicContext includes a method bindContextItem that allows the context item to be supplied. The type of the argument is XQItem: however, Saxon will only accept an XQItem that was created by its own implementations of the factory methods in XQDataFactory.

Unlike JAXP interfaces, XQJ does not include an implementation-independent factory class. Instead, you start the process by calling:

new SaxonXQDataSource()

From the XQDataSource you can call getConnection() to get a connection, and from the connection you can call prepareExpression() to compile a query. The resulting XQPreparedExpression object has a method executeQuery() allowing the query to be evaluated. The result of the query evaluation is an XQSequence, which acts as a cursor or iterator: it has a next() method allowing you to change the current position, and a getItem method allowing you to retrieve the item at the current position. The result of getItem is an XQItem object, and this has methods allowing you to determine the item type, and to convert the item into a suitable Java object or value.

Next