使用带有JDOM / JAXEN / SAXON的XPath搜索XML

时间:2014-11-13 16:04:36

标签: java xml xpath saxon jdom-2

我有一个XML文档,我正在使用JDOM-2.0.5进行解析。以下代码工作正常,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>

Question.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列表是空的!

我的代码出了什么问题?

Question.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 将帮助我推进我的个人小应用程序。

谢谢

2 个答案:

答案 0 :(得分: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,这反过来意味着你必须使用标准{ {1}}将名称空间前缀与URI相关联的方法,这比JDOM更加繁琐 - 您必须定义自己的javax.xml.xpath实现或使用第三方Spring's SimpleNamespaceContext

NamespaceContext

(改编自Saxon&#39; s JDOM2Example.java

答案 1 :(得分:0)

为了完整起见,这里有如何使用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) {
 ....
}