【问题标题】:Search XML using XPath with JDOM/JAXEN/SAXON [duplicate]使用带有 JDOM/JAXEN/SAXON 的 XPath 搜索 XML [重复]
【发布时间】:2014-11-13 16:04:35
【问题描述】:

我确实有一个使用JDOM-2.0.5 解析的XML 文档。以下代码工作正常,bookNodes 列表包含我的 XML 文件中的所有书籍节点:

SAXBuilder builder = new SAXBuilder();

// @see http://xerces.apache.org/xerces-j/features.html
// Disable namespace validation
builder.setFeature("http://xml.org/sax/features/namespaces", false);

Document doc = null;

try {
    doc = builder.build(xmlURL);
} catch (JDOMException | IOException e) {
    e.printStackTrace();
    return null; 
}

// get browse elmt
Element browse = doc.getRootElement().getChild("browse");

// Get all browse's chlidren
List<Element> bookNodes = browse.getChildren("book");

for (Element book : bookNodes) {
    // Do things with the selected nodes
    //...
}

下面是我的 XML 数据示例:

<?xml version="1.0" encoding="utf-8"?> 
<Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com/XMLSchema" version="1">
    <status code="0"/>
    <link>http://www.example.com/books</link>
    <description>Browse, search and ....</description>
    <language>en-us</language>
    <pubDate>Sun, 09 Nov 2014 00:00:02 +0000</pubDate>
    <copyright>Copyright 2014, XXX</copyright>
    <category>Books</category>
    <browse>
        <book id="bk101">
            <author>Gambardella, Matthew</author>
            <title>XML Developer's Guide</title>
            <genre>Computer</genre>
            <price>44.95</price>
            <publish_date>2000-10-01</publish_date>
            <description>An in-depth look at creating applications 
            with XML.</description>
        </book>
        <book id="bk102">
            <author>Ralls, Kim</author>
            <title>The Midnight Rain</title>
            <genre>Fantasy</genre>
            <price>5.95</price>
            <publish_date>2000-12-16</publish_date>
            <description>A former architect battles corporate zombies, 
            an evil sorceress, and her own childhood to become queen 
            of the world.</description>
        </book>
        <book id="bk105">
            <author>Corets, Eva</author>
            <title>The Sundered Grail</title>
            <genre>Fantasy</genre>
            <price>5.95</price>
            <publish_date>2001-09-10</publish_date>
            <description>The two daughters of Maeve, half-sisters, 
            battle one another for control of England. Sequel to 
            Oberon's Legacy.</description>
        </book>
        <book id="bk106">
            <author>Randall, Cynthia</author>
            <title>Lover Birds</title>
            <genre>Romance</genre>
            <price>4.95</price>
            <publish_date>2000-09-02</publish_date>
            <description>When Carla meets Paul at an ornithology 
            conference, tempers fly as feathers get ruffled.</description>
        </book>
    </browse>
</Books>

问题1:

我只想选择包含一些文本的书节点。所以,我使用了 XPath 的查询 //book[contains(./title, 'The')] 和 jaxen-1.1.6,代码如下:

filter = "//book[contains(./title, 'The')]"; // should return 2 elements (2nd and 3rd nodes)

// use the default implementation
XPathFactory xFactory = XPathFactory.instance();

XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());

List<Element> bookNodes = expr.evaluate(doc);

但是bookNodes 列表是空的!

我的代码有什么问题?

问题2:

我将需要更高级的功能来搜索我的 xml 字段,例如使用:

filter = "//book[matches(./title, '^ *XML.*?Developer.*?Guide *$', 'i')]"; // should return 1 element (1st node)

然后我使用支持 XPath 2.0+ 的saxon9he,但我不知道如何使它与 JDOM2 和我上面的代码一起工作。

因此,如果您可以根据我的代码向我介绍如何执行此操作(我已经在 Google 上寻求帮助,但找不到任何帮助)

回答 Q.1 将帮助我了解我做错了什么。但回答 Q.2 将帮助我继续开发我的小型个人应用程序。

谢谢

【问题讨论】:

  • @ThW 旧答案,XPath 类在 JDOM-2 中已弃用

标签: java xml xpath saxon jdom-2


【解决方案1】:

XPath 语言仅在名称空间格式良好的 XML 上定义,如果您尝试在没有名称空间的 XML 树上使用它,可能会产生意想不到的结果。与其忽略命名空间,不如正确使用它们:

SAXBuilder builder = new SAXBuilder();
Document doc = null;

try {
    doc = builder.build(xmlURL);
} catch (JDOMException | IOException e) {
    e.printStackTrace();
    return null; 
}

Namespace ns = Namespace.getNamespace("http://www.example.com/XMLSchema");

// get browse elmt
Element browse = doc.getRootElement().getChild("browse", ns);

// Get all browse's chlidren
List<Element> bookNodes = browse.getChildren("book", ns);

for (Element book : bookNodes) {
    // Do things with the selected nodes
    //...
}

对于 XPath,您需要将命名空间 URI 绑定到前缀:

filter = "//ns:book[contains(./ns:title, 'The')]";

// use the default implementation
XPathFactory xFactory = XPathFactory.instance();

XPathBuilder<Element> builder = new XPathBuilder(filter, Filters.element());
builder.setNamespace("ns", "http://www.example.com/XMLSchema");
XPathExpression<Element> expr = builder.compileWith(xFactory);

List<Element> bookNodes = expr.evaluate(doc);

关于问题 2,Saxon 的 XPath 引擎可以使用 JDOM2 树,但您必须使用 Saxon 的 XPath API 而不是 JDOM,这反过来意味着您必须使用标准的javax.xml.xpath 将命名空间前缀与 URI 关联的方式,即比 JDOM 麻烦得多 - 您必须定义自己的 NamespaceContext 实现或使用第三方实现,例如 Spring's SimpleNamespaceContext。

JDOM2DocumentWrapper docw =
        new JDOM2DocumentWrapper(doc, config); // net.sf.saxon.option.jdom2

XPathEvaluator xpath = new XPathEvaluator(); // net.sf.saxon.xpath
SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
nsCtx.bindNamespaceUri("ns", "http://www.example.com/XMLSchema");
xpath.setNamespaceContext(nsCtx);
List<?> bookNodes = (List<?>)xpath.evaluate(
   "//ns:book[matches(./ns:title, '^ *XML.*?Developer.*?Guide *$', 'i')]", docw,
   XPathConstants.NODESET);

(改编自撒克逊人的JDOM2Example.java)

【讨论】:

  • Q.1 很好。但是对于 Q.2,根据您的示例链接,某些导入无法像 JDOM2DocumentWrapper, ProfessionalConfiguration 那样解决...我正在使用 Saxon-HE 9.6
  • 虽然 Saxon 支持 javax.xml.xpath API,但它也有自己的 s9api API,这对于定义命名空间绑定之类的简单任务更加方便:xPathCompiler.declareNamespace(prefix, uri)。见saxonica.com/documentation/#!javadoc/net.sf.saxon.s9api/…
  • @Enissay 示例代码使用 Saxon PE,我的版本通过使用 XPathEvaluator 的无参数构造函数适用于 HE。但正如 Michael 所指出的,s9api 方法更简单。
【解决方案2】:

为了完整起见,下面是使用 Saxon 的 s9api 接口的方法:

Processor proc = new Processor();
XdmNode docw = proc.newDocumentBuilder().wrap(doc);
XPathCompiler xpath = proc.newXPathCompiler();
xpath.declareNamespace("ns", "http://www.example.com/XMLSchema");
XdmValue bookNodes = xpath.evaluate(
   "//ns:book[matches(./ns:title, '^ *XML.*?Developer.*?Guide *$', 'i')]", docw);
for (XdmItem book : bookNodes) {
 ....
}

【讨论】:

  • 我使用了new Processor(false)。在以下行中,我收到错误 java.lang.ClassCastException: net.sf.saxon.value.ObjectValue cannot be cast to net.sf.saxon.om.NodeInfo at net.sf.saxon.s9api.DocumentBuilder.wrap(DocumentBuilder.java:511)
  • 听起来好像您正在使用“开箱即用”不支持 JDOM2 的 Saxon-HE,但如果您想节省 50 英镑的成本,您可以自行配置PE 许可证。
猜你喜欢
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 2013-04-20
相关资源
最近更新 更多