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


The juicers.xml file now has xmlns


<?xml version="1.0"?>

    <name>OJ Home Juicer</name>
    <description>There&apos;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&apos;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.
    <warranty>lifetime warranty</warranty>


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

2 answers

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";


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";


You can set the namespace id juicers




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);




All Articles