Reputation: 809
I wondered how it was possible to get the content of a SOAP response body child when the child tag looks like this:
<sth:x>...</sth:x>
In the Oracle docs I found how to loop all Elements with a specific name. But therefore I need to create an Element first that specifies the name of the tag I want to search.
How do I create an element looking like the one above? I know how to make one like this:
<sth:id sth="asdf">
But that doesn't really work. Here is the server-response I attempt to read.
<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:Header/>
<soapenv:Body>
<ns5:loginResponse xmlns:ns5="x">
<ns5:id>Value I am looking for</ns5:id>
<ns5:rc>0</ns5:rc>
</ns5:loginResponse>
</soapenv:Body>
</soapenv:Envelope>
Thanks for your help :)
Upvotes: 0
Views: 4376
Reputation: 6366
Try this:
String xml = "YourXMl";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("x","id");
System.err.println(nodes.item(0).getChildNodes().item(0).getNodeValue());
There are two important things factory.setNamespaceAware(true);
- to turn on support for xml namespaces.
doc.getDocumentElement().getElementsByTagNameNS("x","id");
To get element using namespace uri and element name. And here is <ns5:loginResponse xmlns:ns5="x">
declaration of namespace uri. x
is uri ns5
is namespace.
Upvotes: 1
Reputation: 809
I found the answer:
The Element in question was within another SOAPBodyElement. So looping through both elements gave me the correct Value:
body = reply.getSOAPBody();
Iterator replyIt = body.getChildElements();
while(replyIt.hasNext()){
SOAPBodyElement replysbe = (SOAPBodyElement) replyIt.next();
Iterator replyIt2 = replysbe.getChildElements();
SOAPElement sentSE = (SOAPElement) replyIt2.next();
sessionID = sentSE.getValue();
}
Upvotes: 0