Querying Data from XML Files or DOM Trees


In the previous section, we queried data in a relational database. Now let's query an XML file.

Querying an XML File

Suppose you want to query holdings for a specific customer identified by the userid element in a file named holdings.xml, which looks like this:

<holdings> 
   <row> 
      <userid>Jonathan</userid> 
      <stockticker>AMZN</stockticker> 
      <shares>3000</shares> 
   </row> 
   <row> 
      <userid>Minollo</userid> 
      <stockticker>EBAY</stockticker> 
      <shares>4000</shares> 
   </row> 
</holdings> 

Here's an XQuery expression that returns holdings for a customer named Jonathan:

doc("holdings.xml")/holdings/row[userid="Jonathan"] 

Suppose we wanted to return holdings for other customers. If you write an XQuery with an external variable that provides the name of the customer whose holdings you require, the Java application can specify the name of the customer before it executes the query. If you use another external variable to represent the document, the Java application can pass any document to the query at runtime. For example:

declare variable $u as xs:string external;  
declare variable $d as document-node(element(*, xs:untyped)) external;  
$d/holdings/row[userid=$u]  

Querying a DOM

Now, let's write Java code to create a DOM tree and bind it to the variable $d. Use the following code to create a DOM tree.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
factory.setNamespaceAware(true); 
 
DocumentBuilder parser = factory.newDocumentBuilder(); 
File xmlFile = new File("holdings.xml"); 
Document document = parser.parse(xmlFile); 

Once you create a DOM tree, you can use XQJ to bind the DOM tree to a variable and query it. First, you create an expression object, and then bind the document to the variable $d for this expression.

XQConnection conn = ds.getConnection(); 
XQExpression xqExpression = conn.createExpression(); 
xqExpression.bindNode(new QName("d"), document); 

Now, execute the expression and output the result:

FileReader fileReader = new FileReader("flwor.xq"); 
 
XQSequence xqSequence = xqExpression.executeQuery(fileReader); 
System.out.println(xqSequence.getSequenceAsString()); 

Other similar examples can be found in the ExternalVariables example.

Querying a Directory

You can also query XML files in a directory. See Querying Multiple Files in a Directory for information about this feature. An example can be found in the XMLQuery example.