-2
過去兩天我一直堅持這個任務,並沒有通過不同的文章得到任何明確的解決方案。所以請給我一步一步的代碼來檢索XML中存在的XPath值。如何閱讀java中的XML xpath
我的XML是
<bookstore>
<book>
<int name="sno">1</int>
<str name="author">J K. Rowling</str>
<int name="price">29.99</int>
<str name="subauthor">J K</str>
</book>
<book>
<int name="sno">2</int>
<str name="author">J K. Rowling</str>
<int name="price">29.99</int>
<str name="subauthor">hamilton</str>
</book>
</bookstore>
在這個XML我需要每個作者,價格和subauthor值。 我預期的結果是:
(author-J K. Rowling,price-29.99,subauthor-j k)
再怎麼從這個XML得到subauthor的最後一個值。
我的java代碼來得到這個值是行不通的。它只拋出一個例外。
public gettheXMLvalues() {
try {
NodeList nodeLst1 = doc.getElementsByTagName("doc");
for (int i = 0; i < nodeLst1.getLength(); i++) {
Node node = nodeLst1.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList nodes = element.getElementsByTagName("//str[@name='author']").item(0).getChildNodes();
node = (Node) nodes.item(0);
System.out.println("ELEMETS " + element.getTextContent());
System.out.println("Author" + node.getNodeValue());
}
} catch(Exception e){
system.out.println("Exception "+e);
}
}
請給我一個解決方案,使作者,價格和每個book.I的subauthor價值試過很多事情得到結果,但不幸的是我沒有得到的結果。請給我清楚的解決方案。
什麼異常? – fGo
發佈異常跟蹤 –
我不認爲'getElementsByTagName'方法接受Xpath表達式。你可以更好地做這樣的事情: 'XPathExpression expr = xpath.compile(「/ bookstore/book/int [@ name ='price']/url」); NodeList nl =(NodeList)expr.evaluate(doc,XPathConstants.NODESET);'。看看這個http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java – fGo