使用Xpath解析XML时卡住

纳德姆

从下面提到的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)
青蛙

您需要更改表达式,下面的代码可以正常工作:

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章