简体   繁体   English

使用Xpath解析XML时卡住

[英]Stuck while parsing XML using Xpath

From the below mentioned xml I need to extract the value of tag dp:result and store it into a string 从下面提到的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>

I am using this code to do it. 我正在使用此代码来做到这一点。 where Resp is a string containing the above mentioned xml 其中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);

However I am getting this error 但是我收到此错误

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)

You need to change your expression, below code is working: 您需要更改表达式,下面的代码可以正常工作:

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);
    }
}

output 产量

Result:: OK

And here is my Xml: 这是我的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM