使用 BaseX 查询 XML 文件

Anu*_*kar 5 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));
Run Code Online (Sandbox Code Playgroud)

现在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>
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

Jen*_*rat 3

除了 Chrstian 的答案之外,您还必须声明一个默认元素名称空间,或者在每次寻址元素时使用该名称空间(如果您的文档中有多个名称空间,您可能需要这样做)。

默认元素命名空间使您能够像上面那样编写查询:

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

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

declare namespace juicers="http://www.juicers.org";
doc('xmlfiles/juicers.xml')//juicers:image
Run Code Online (Sandbox Code Playgroud)

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