使用JAVA切片SOAP响应

时间:2016-04-24 17:25:03

标签: java xml soap

我需要得到一个SOAP响应的主体,但是身体有一个孩子是我需要的内容的父母,我不知道如何让这个孩子的身体。

响应:

<?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>

我想要的是“bairro”,“cep”,“cidade”等。

我正在使用代码来获得回复:

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

1 个答案:

答案 0 :(得分:0)

我使用getElementsByTagName()获取<return>元素,然后使用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
}

输出

bairro = Asa Norte
cep = 70002900
cidade = Brasilia
complemento = 
complemento2 = 
end = SBN Quadra 1 Bloco A
id = 0
uf = DF