Sandeep
Sandeep

Reputation: 41

Soap response message parsing using XPath

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.

Upvotes: 1

Views: 9402

Answers (2)

Wayne
Wayne

Reputation: 60414

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.

Upvotes: 2

newtover
newtover

Reputation: 32074

You should add a NamespaceContext to your xpath expression.

Upvotes: 1

Related Questions