【发布时间】: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