从下面提到的xml我需要提取标签dp:result的值并将其存储到字符串中
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<dp:response xmlns:dp="http://www.datapower.com/schemas/management">
<dp:timestamp>2015-07-09T04:45:15-04:00</dp:timestamp>
<dp:result>OK</dp:result>
</dp:response>
</env:Body>
</env:Envelope>
我正在使用此代码来执行此操作。其中Resp是包含上述xml的字符串
XPath xxPath = XPathFactory.newInstance().newXPath();
String expression = "/env:Envelope/env:Body/dp:response/dp:result";
String Status = xxPath.compile(expression).evaluate(Resp);
System.out.println(Status);
但是我收到此错误
java.lang.ClassCastException: java.lang.String cannot be cast to org.w3c.dom.Node
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.evaluate(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.evaluate(Unknown Source)
at com.ibm.dp.client.HTTPSClient.main(HTTPSClient.java:337)
答案 0 :(得分:0)
您需要更改表达式,以下代码正常工作:
public class XPathTest {
public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("file.xml"));
XPath xxPath = XPathFactory.newInstance().newXPath();
String expression = "/Envelope/Body/response/result";
javax.xml.xpath.XPathExpression cc = xxPath.compile(expression);
String result = cc.evaluate(doc);
System.out.println("Result:: " + result);
}
}
输出
Result:: OK
这是我的Xml:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<dp:response xmlns:dp="http://www.datapower.com/schemas/management">
<dp:timestamp>2015-07-09T04:45:15-04:00</dp:timestamp>
<dp:result>OK</dp:result>
</dp:response>
</env:Body>
</env:Envelope>