使用BaseX查询XML文件

时间:2012-03-31 19:53:33

标签: xml xquery basex

我正在使用BaseX原生XML数据库来查询XML文件。 我正在使用BaseX文档中提供的BaseXClient.java文件。我正在启动basex服务器并使用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));

现在juicers.xml文件有xmlns个信息。

<?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>

如果我没有在XML实例文件(juicers.xml)中提供xmlns,则会返回正确的结果。 但是如果XML实例文件中包含xmlns,则抛出以下异常。

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)

如何使用xmlns查询XML实例文件?有出路吗?有没有其他方法可以从Java运行xquery

2 个答案:

答案 0 :(得分:3)

除了Chrstian的答案之外,你必须要么声明一个默认元素名称空间,要么每次你对一个元素进行处理时都使用名称空间(如果你有多个名字空间,你可能想要这样做)文件)。

默认的元素名称空间使您可以像上面那样编写查询:

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

如果您不想将juicers用作默认元素名称空间,请将其声明为名称空间并在元素级别引用它:

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

您可以任意设置名称空间标识juicers

答案 1 :(得分:1)

您需要在查询前添加XQUERY命令:

System.out.println(session.execute("XQUERY " + query));

另一种选择是创建一个“查询”实例并在此之后调用query.execute()

BaseXClient.Query query = session.query(query);
System.out.println(query.execute())