【发布时间】:2013-05-27 07:23:42
【问题描述】:
过去两天我一直在做这个任务,我没有通过不同的文章得到任何明确的解决方案。所以请给我一步一步的代码来检索 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 中,我需要每个作者、价格和副作者值。 我的预期结果是:
(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);
}
}
请给我一个解决方案来获取每本书的作者、价格和子作者的价值。我尝试了很多方法来获取结果,但不幸的是我没有得到结果。请给我明确的解决方案。
【问题讨论】:
-
发布异常跟踪
-
我不认为
getElementsByTagName方法接受Xpath 表达式。你最好做这样的事情XPathExpression expr = xpath.compile("/bookstore/book/int [@name='price']/url"); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);。看看这个stackoverflow.com/questions/2811001/… -
The Java XPath API 在 developerWorks 上
-
我需要清晰的代码来解决上述问题。我需要读取作者的值,每个文档标签的价格。给我示例代码