Invoking XQuery using the XQJ API

XQJ (XQuery API for Java, also known as JSR 225) is a vendor-neutral API for invoking XQuery from Java applications. The Final Release (1.0) is published at http://jcp.org/en/jsr/detail?id=225. Saxon includes a complete and conformant implementation of this API.

For information on how to use the API, please see the JSR 225 documentation.

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 bindAtomicValue that allows the value of a variable or 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().

This constructor will create a new configuration, which will be an EnterpriseConfiguration or ProfessionalConfiguration if Saxon-EE or Saxon-PE is in use. As an alternative, there is also a constructor that allows a specific pre-exising configuration to be used.

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.