Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying XML files using BaseX

Tags:

xml

xquery

basex

I am using BaseX native XML database to query XML files. I am using the BaseXClient.java file provided in the BaseX documentation. I am starting the basex server and connecting to 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));

Now the juicers.xml file 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&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.
    </description>
    <warranty>lifetime warranty</warranty>
    <cost>41.95</cost>
    <retailer>http://www.thewhitewhale.com/oj.htm</retailer>
</juicer>
</juicers>

If I don't give the xmlns in XML instance file (juicers.xml), it returns me correct results. But if xmlns is included in 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 query XML instances files with xmlns? Is there a way out? Is there any other way to run xquery from Java?

like image 791
Anup Warnulkar Avatar asked Oct 08 '22 06:10

Anup Warnulkar


1 Answers

In addition to Chrstian's answer, you have to either declare a default element namespace or use the namespace each time you address an element (you probably want to do this if you'd have multiple namespaces in your document).

The default element namespace enables you to write your query like you did above:

declare default element namespace "http://www.juicers.org";
doc('xmlfiles/juicers.xml')//image

If you do not want to use juicers as default element namespace, declare it as namespace and reference it at element-level:

declare namespace juicers="http://www.juicers.org";
doc('xmlfiles/juicers.xml')//juicers:image

You can set the namespace identifier juicers arbitrarily.

like image 99
Jens Erat Avatar answered Oct 12 '22 12:10

Jens Erat