gpt4 book ai didi

java - 使用 Xpath 解析 XML 时卡住

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:05 24 4
gpt4 key购买 nike

从下面提到的 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);
}
}

output

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>

关于java - 使用 Xpath 解析 XML 时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com