1

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

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.

stema
  • 90,351
  • 20
  • 107
  • 135
Sandeep
  • 41
  • 3
  • 6
  • You write wrong name of Node (you include namespace in it). Check this question: http://stackoverflow.com/questions/112601/select-element-in-a-namespace-with-xpath – Zernike Nov 16 '11 at 06:17
  • you may can find answer here: [finding tags in soap xml directly by name](https://stackoverflow.com/a/65397403/8496599) – Witold Krzemiński Dec 21 '20 at 17:58
  • You may find answer hehe: [enter link description here](https://stackoverflow.com/a/65397403/8496599) – Witold Krzemiński Dec 21 '20 at 18:03

2 Answers2

2

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:

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

Community
  • 1
  • 1
Wayne
  • 59,728
  • 15
  • 131
  • 126
1

You should add a NamespaceContext to your xpath expression.

newtover
  • 31,286
  • 11
  • 84
  • 89