1
說我得到了下面的數據庫(通常他們會更大):如何在Java的XPath的匹配索引值
<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個作者。因此,我無法通過使用每個列表中的相同索引值進行循環來打印相應的書籍/作者組合(它只對第一個條目有效,然後以1爲單位),並在出現空指針異常時最終給出空指針異常在作者列表中沒有更多條目)。有沒有辦法解決這個問題?
感謝您的閱讀。
注:一段代碼至今:
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());
}
謝謝,這正是訣竅! – blaughli 2012-04-03 20:03:30
我在Java中執行此操作時遇到問題。任何意見,將不勝感激。 – blaughli 2012-04-03 20:40:55