我正在尝试从 SOAP 响应中提取节点 GoodEmail 的值。似乎无论我尝试什么,我总是得到 org.apache.commons.jxpath.JXPathNotFoundException。
SOAP 响应:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<VerifyEmailResponse xmlns="http://ws.cdyne.com/">
<VerifyEmailResult>
<ResponseText>Invalid Email Address</ResponseText>
<ResponseCode>0</ResponseCode>
<LastMailServer/>
<GoodEmail>false</GoodEmail>
</VerifyEmailResult>
</VerifyEmailResponse>
</soap:Body>
</soap:Envelope>
Java 代码:
String payload = message.getPayloadAsString(); //The SOAP response
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(payload));
Document doc = db.parse(is);
JXPathContext context = JXPathContext.newContext(doc);
String jxpathReply = (String) context.getValue("//soap:Envelope/soap:Body/VerifyEmailResponse/VerifyEmailResult/GoodEmail");
对我来说,错误代码似乎表明 xpath 过滤器是错误的。我尝试了几种不同的方法,但都无法得到正确的结果。我做错了什么?
最佳答案
这是 XPath 中最多的常见问题解答。搜索“xpath默认命名空间”
,您会找到很多好的答案。
简单的解释是,在 XPath 中,任何无前缀的名称都被视为属于“无命名空间”。因此,如果我们想要指定属于某个命名空间(包括默认命名空间)的元素的名称,这些名称必须带有前缀,并且指定的前缀必须关联起来(使用特定的 XPath 引擎 API)与特定节点所在的命名空间的命名空间-uri。
因此,表达式可能是这样的:
/soap:Envelope/soap:Body/x:VerifyEmailResponse/x:VerifyEmailResult/x:GoodEmail
其中前缀“x”
与命名空间“http://ws.cdyne.com/”关联(通过“注册”此命名空间关联)
关于java - 用于过滤 SOAP 消息的 JXPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7836057/