繁体   English   中英

使用BaseX查询XML文件

[英]Querying XML files using 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

除了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随意。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM