Querying XML Files with BaseX
I am using BaseX XML database to query XML files. I am using the BaseXClient.java file listed in the BaseX documentation. I start the base server and connect to the server using BaseXClient.java.
// create session
final BaseXClient session = new BaseXClient("localhost", 1984, "admin", "admin");
String query = "doc('xmlfiles/juicers.xml')//image";
// version 1: perform command and print returned string
System.out.println(session.execute(query));
The juicers.xml file now has xmlns
information.
<?xml version="1.0"?>
<juicers
xmlns="http://www.juicers.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.juicers.org
juicers.xsd">
<juicer>
<name>OJ Home Juicer</name>
<image>images\mighty_oj.gif</image>
<description>There's just no substitute for a properly squeezed
orange in the morning. So delicate and refreshing. The finest hotels
use mechanical juicers of this type for their most discriminating
guests. This is the largest selling juicer of its kind. It's a
beautiful little all-metal piece in baked enamel and polished chrome;
it even won the Frankfurt Fair Award for its design. Uses no
electricity and produces no non-recyclable waste as do frozen juices.
</description>
<warranty>lifetime warranty</warranty>
<cost>41.95</cost>
<retailer>http://www.thewhitewhale.com/oj.htm</retailer>
</juicer>
</juicers>
If I have not provided xmlns
in the XML instance file (juicers.xml) it will return correct results to me. But if xmlns
included in the XML instance file, the following exception is thrown.
java.io.IOException: Stopped at line 1, column 3:
Expecting command.
at org.basex.api.BaseXClient.execute(BaseXClient.java:73)
at org.basex.api.BaseXClient.execute(BaseXClient.java:84)
at org.basex.api.Example.main(Example.java:31)
How do I handle XML instance files using xmlns
? Is there a way out? Is there any other way to run xquery
from Java?
source to share
In addition to Chrstian's answers, you need to either declare the element's default namespace, or use the namespace every time you access an element (you probably want to do this if you have multiple namespaces in your document).
The default element namespace allows you to write your query the way you did:
declare default element namespace "http://www.juicers.org";
doc('xmlfiles/juicers.xml')//image
If you don't want to use juicers as the default element namespace, declare it as a namespace and reference it at the element level:
declare namespace juicers="http://www.juicers.org";
doc('xmlfiles/juicers.xml')//juicers:image
You can set the namespace id juicers
arbitrarily.
source to share
You need to prefix your request with the command XQUERY
:
System.out.println(session.execute("XQUERY " + query));
Another option is to create an instance of "Request" and then call query.execute()
:
BaseXClient.Query query = session.query(query);
System.out.println(query.execute())
source to share