使用 XPath 解析 Soap 响应消息 [英] Soap response message parsing using XPath

查看:78
本文介绍了使用 XPath 解析 Soap 响应消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 xpath 解析soap响应,在响应消息的一些代码下方.

I try to parse soap response using xpath , below the some code of response message.

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:Get__CompIntfc__CI_PERSONAL_DATAResponse
xmlns:ns1="http://xmlns.oracle.com/Enterprise/Tools/schemas/M985361.V1">
<ns1:PROP_EMPLID>AA0001</ns1:PROP_EMPLID>
<ns1:PROP_LAST_NAME>Adams</ns1:PROP_LAST_NAME><ns1:PROP_FIRST_NAME>Kimberly</ns1:PROP_FIRST_NAME>
</ns1:Get__CompIntfc__CI_PERSONAL_DATAResponse >
</soapenv:Body>
</soapenv:Envelope>

我尝试像...一样解析它

I try to parse it like...

DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
     domFactory.setNamespaceAware(true); 
     DocumentBuilder builder = domFactory.newDocumentBuilder();
     ByteArrayOutputStream out = new ByteArrayOutputStream(); 
     response.writeTo(out); 
InputStream is = new ByteArrayInputStream( out.toByteArray() ); 
Document doc = builder.parse( is );
        XPathExpression expr = xpath.compile("//ns1:PROP_EMPLID/text()");
           Object res = expr.evaluate(doc, XPathConstants.NODESET);
           NodeList nodes = (NodeList) res;
    for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue()); 
       }

它没有给出所需的值AA0001"但是当我使用 xpath.compile("///*/text()") 时,它会正确打印所有文本节点值.

It not give the required value "AA0001" but when i use xpath.compile("//*/text()") it prints all text node value properly.

请告诉我有什么问题,因为我想要响应中的一些特定值而不是所有文本值.

Please tell me what is the problem because I want some specific values from response not all text values.

推荐答案

您正在尝试检索由前缀 ns1 表示的命名空间中的节点,但您的应用程序不知道 这个前缀代表什么,因为你没有将此名称与任何实际的命名空间相关联.在 Java 中执行此操作的方法(如@newtover 所述)是使用 xpath 对象注册 javax.xml.namespace.NamespaceContext 的实例.像这样:

You're attempting to retrieve a node in the namespace represented by the prefix ns1, but your application has no idea what this prefix represents, because you haven't associated this name with any actual namespace. The way to do this in Java (as mentioned by @newtover) is to register an instance of a javax.xml.namespace.NamespaceContext with your xpath object. Something like this:

xpath.setNamespaceContext(namespaces);

遗憾的是,此接口没有默认实现.你需要自己动手.一个完整的例子可以在这里找到:

Unfortunately, there is no default implementation of this interface. You'll need to roll your own. A complete example can be found here:

...或通过关注@newtover 的链接.

...or by following @newtover's link.

这篇关于使用 XPath 解析 Soap 响应消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆