了迭代的节点的XPath的价值我有一个XML掌握在Java中
<?xml version="1.0" encoding="UTF-8"?>
<information>
<person id="1">
<name>Deep</name>
<age>34</age>
<gender>Male</gender>
</person>
<person id="2">
<name>Kumar</name>
<age>24</age>
<gender>Male</gender>
</person>
<person id="3">
<name>Deepali</name>
<age>19</age>
<gender>Female</gender>
</person>
<!-- more persons... -->
</information>
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//information/person[0]/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODE);
Node node = (Node) result;
System.out.println(node.getNodeValue());
,我需要提取的第一人我想上面的代码名称它给例外任何一个可以帮我在这,
修订 异常
Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to javax.xml.soap.Node
at xml.main(xml.java:33)
修订ANSWER
XPathExpression expr = xpath.compile("//information/person[1]/name");
String str = (String) expr.evaluate(doc, XPathConstants.STRING);
System.out.println(str);
什么异常? – McDowell 2012-04-11 18:12:50
拉梅什,假设我去看了医生,说:“我觉得恶心,但我不会告诉你我的症状,你能帮我吗?” – LarsH 2012-04-11 18:48:18
对不起,不提供例外。我已经更新了这个问题,请看看 – Ramesh 2012-04-12 04:06:37