【问题标题】:how to match index values in XPath Java如何在 XPath Java 中匹配索引值
【发布时间】:2012-04-17 11:48:16
【问题描述】:

假设我有以下数据库(通常它们会更大):

<inventory>
<book year="2000">
    <title>Snow Crash</title>
    <author>Neal Stephenson</author>
    <publisher>Spectra</publisher>
    <isbn>0553380958</isbn>
    <price>14.95</price>
</book>

<book year="2005">
    <title>Burning Tower</title>
    <author></author>
    <publisher>Pocket</publisher>
    <isbn>0743416910</isbn>
    <price>5.99</price>
</book>

<book year="1995">
    <title>Zodiac</title>
    <author>Neal Stephenson</author>
    <publisher>Spectra</publisher>
    <isbn>0553573862</isbn>
    <price>7.50</price>
</book>

<!-- more books... -->

我想获取所有的书名和作者,然后打印出书名和通讯作者。请注意,第二个条目没有列出作者。我发现 XPath 将创建一个包含 3 本书的列表,但只有 2 个作者。因此,我无法通过使用每个列表中的相同索引值进行循环来打印相应的 Book/Author 组合(它仅适用于第一个条目,然后下降一个,并最终在有时给出空指针异常作者列表中没有更多条目)。有没有办法解决这个问题?

感谢阅读。

注:到目前为止的一段代码:

XPathExpression expr1 = xpath.compile("//pre:entry/pre:title/text()");
XPathExpression expr2 = xpath.compile("//pre:entry/pre:author/text()");

Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET);

NodeList nodes1 = (NodeList) result1;
NodeList nodes2 = (NodeList) result2;

for (int i = 0; i < nodes1.getLength(); i++) {
   System.out.println(nodes1.item(i).getNodeValue());
   System.out.println(nodes2.item(i).getNodeValue());
}

【问题讨论】:

    标签: java xml list xpath indexing


    【解决方案1】:

    您必须迭代 throw 所有 book 元素,然后在每个 book 元素中获取 titleauthor 元素,例如伪代码:

    var bookNodes = XPath.select('//pre:book');
    foreach book in booknodes
        var title = book.select('pre:title');
        var author = book.select('pre:author');
    

    【讨论】:

    • 我在 Java 中实现它时遇到了麻烦。任何建议将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多