I need to get the body of a SOAP response, but the body have a child that is parent of the content I need, and I don't know how to acess this child of the body.
Response:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:consultaCEPResponse xmlns:ns2="http://cliente.bean.master.sigep.bsb.correios.com.br/">
<return>
<bairro>Asa Norte</bairro>
<cep>70002900</cep>
<cidade>Brasilia</cidade>
<complemento />
<complemento2 />
<end>SBN Quadra 1 Bloco A</end>
<id>0</id>
<uf>DF</uf>
</return>
</ns2:consultaCEPResponse>
</soap:Body>
</soap:Envelope>
What I want is "bairro", "cep", "cidade", etc.
Code I'm using to get response:
SOAPMessage rp = conn.call(msg, urlval);
// I tried this, but didn't work
//QName bodyName = new QName("http://cliente.bean.master.sigep.bsb.correios.com.br/", "consultaCEPResponse", "ns2");
Iterator itr = rp.getSOAPBody().getChildElements(bodyName);
while (itr.hasNext()) {
Node node = (Node) itr.next();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element ele = (Element) node;
System.out.println("\n" + ele.getNodeName() + " = " + ele.getTextContent());
}
}
I'd use getElementsByTagName()
to get the <return>
element, and then just find its children using getChildNodes()
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:consultaCEPResponse xmlns:ns2=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\"><return><bairro>Asa Norte</bairro><cep>70002900</cep><cidade>Brasilia</cidade><complemento /><complemento2 /><end>SBN Quadra 1 Bloco A</end><id>0</id><uf>DF</uf></return></ns2:consultaCEPResponse></soap:Body></soap:Envelope>";
SOAPMessage rp = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(xml.getBytes()));
NodeList returnNodes = rp.getSOAPBody().getElementsByTagName("return");
if (returnNodes.getLength() == 1) {
Node returnNode = returnNodes.item(0);
NodeList elements = returnNode.getChildNodes();
for (int i = 0; i < elements.getLength(); i++) {
Node node = elements.item(i);
System.out.println(node.getNodeName() + " = " + node.getTextContent());
}
} else {
// handle empty response case
}
Output
bairro = Asa Norte
cep = 70002900
cidade = Brasilia
complemento =
complemento2 =
end = SBN Quadra 1 Bloco A
id = 0
uf = DF
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.