Java 使用XPath解析Soap响应消息
我尝试使用Java 使用XPath解析Soap响应消息,java,xpath,Java,Xpath,我尝试使用xpath,在响应消息的某些代码下面解析soap响应 <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/
xpath
,在响应消息的某些代码下面解析soap响应
<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>
AA0001
亚当斯金伯利
我试着解析它,就像
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());
}
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder=domFactory.newDocumentBuilder();
ByteArrayOutputStream out=新建ByteArrayOutputStream();
答复.书面通知(发出);
InputStream is=newbytearrayinputstream(out.toByteArray());
文档doc=builder.parse(is);
XPathExpression expr=xpath.compile(“//ns1:PROP_EMPLID/text()”;
Object res=expr.evaluate(doc,XPathConstants.NODESET);
节点列表节点=(节点列表)res;
对于(int i=0;i
它没有给出所需的值“AA0001”
但当我使用xpath.compile(“//*/text()”)
时,它会正确地打印所有文本节点值
请告诉我问题出在哪里,因为我希望从响应中获得一些特定值,而不是所有文本值。您应该在xpath表达式中添加一个值。您试图检索前缀ns1表示的命名空间中的节点,但您的应用程序不知道该前缀表示什么,因为您尚未将此名称与任何实际命名空间关联。在Java中实现这一点的方法(如@newtover所述)是使用
xpath
对象注册javax.xml.namespace.NamespaceContext
的实例。大概是这样的:
xpath.setNamespaceContext(namespaces);
不幸的是,此接口没有默认实现。你需要自己动手。可以在此处找到完整的示例:
…或者通过跟随@newtover的链接。您写入了错误的节点名称(其中包含名称空间)。勾选这个问题:你可以在这里找到答案:你可以找到答案呵呵: