Channels ▼
RSS

Database

XQuery

Source Code Accompanies This Article. Download It Now.


Using XQuery From Java

The eXist sandbox is an excellent learning tool and can be useful for composing and executing ad hoc queries; however, as you surely discovered when you used SQL, the real power of XQuery comes when it is used in an application. QueryExample.java (available online; see www.ddj.com/code/) is a Java program from the eXist Developer's Guide that can be used to execute XQueries. There are many implementations of XQuery. Because we had already installed eXist to use the sandbox, we chose the XML:DB API that eXist uses. This API can work with any native or XML-enabled database for which a suitable driver has been written. If you examine the Java code, you see that it is roughly analogous to using JDBC. You start by using the following code to load the driver:


String driver =    "org.exist.xmldb.DatabaseImpl";
Class cl = Class.forName(driver);	
  Database database =      (Database)cl.newInstance();
DatabaseManager.registerDatabase   (database);


The only difference between this code and its JDBC counterpart is the last line, which registers the Database object with the DatabaseManager. Each vendor delivers its own implementation of Database, which is the encapsulation of the database driver functionality that is necessary to access an XML database. The DatabaseManager class provides access to a Collection. The Collection interface represents a collection of Resources stored in an XML database. The Resource interface represents a container for data stored within the database.

Next, you get a Collection object using this code:


Collection col =    DatabaseManager.getCollection(
"xmldb:exist://localhost:8080   /exist/xmlrpc/db"


The URI starts with xmldb: and the rest is vendor specific, but the overall format resembles the URIs you have used in JDBC.

From the collection, you obtain a Service instance:


XPathQueryService service =
  (XPathQueryService) col.getService   ("XPathQueryService", "1.0");


XPathQueryService is an implementation of the Service interface that enables the execution of XPath queries within the context of a Collection or against a single XML Resource stored in the Collection. The Service interface is equivalent to the Statement interface in JDBC.

You then execute the query using the following statement:


ResourceSet result =    service.query(args[0]);


The argument to the query() method is a string whose contents is the XQuery. In our example, rather than hardcoding an XQuery, we generalized the program by accepting the XQuery as a command-line argument. The query() method returns a ResourceSet, which is similar to the ResultSet in JDBC. We complete our program by iterating over the ResourceSet and displaying the content of each Resource it contains. The code looks like this:


ResourceIterator i =    result.getIterator();
while(i.hasMoreResources()) {
  Resource r = i.nextResource();
    System.out.println       ((String)r.getContent());
    }


QueryResults (available online) shows the results obtained when you run the program using this command-line argument:


doc("musicians.xml")/musicians/musician[birthDate>="1960-01-01" and birthDate<"1965-01-01"] 


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video