在soap响应中深入获取元素

时间:2016-05-08 12:57:59

标签: java soa saaj

好的,所以我得到以下肥皂回复:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <GetCustomerDetailsByDeviceNumberResponse xmlns="http://services.domain.com/SelfCare">
            <GetCustomerDetailsByDeviceNumberResult xmlns:a="http://datacontracts.domain.com/SelfCare" 
              xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <a:AuditReferenceNumber i:nil="true"/>
                    <a:accounts>
                        <a:Account>
                            <a:lastInvoiceAmount>0</a:lastInvoiceAmount>
                        <a:lastInvoiceDate>0001-01-01T00:00:00</a:lastInvoiceDate>
                    </a:Account>
                </a:accounts>
            </GetCustomerDetailsByDeviceNumberResult>
        </GetCustomerDetailsByDeviceNumberResponse>
    </s:Body>
</s:Envelope>

我试图通过这段代码获得<a:lastInvoiceDate></a:lastInvoiceDate>的值:

SOAPBody sBody = response.getSOAPBody();
QName gcdbdbr = new QName("http://services.domain.com/SelfCare", "GetCustomerDetailsByDeviceNumberResponse");
java.util.Iterator iterator = sBody.getChildElements(gcdbdbr);
while(iterator.hasNext()){
      NodeList nodeList = sBody.getElementsByTagName("lastInvoiceDate");
      Element element = (Element) nodeList.item(0);
      Node child = element.getFirstChild();
      String data = child.getTextContent();
      System.out.println(data);
}

但它是空的。

如何获得<a:lastInvoiceDate>的价值?

2 个答案:

答案 0 :(得分:1)

您的代码似乎很好,但是当您使用getElementsByTagName()时,您还必须在字符串参数中包含命名空间,如下所示:

...    
NodeList nodeList = sBody.getElementsByTagName("a:lastInvoiceDate");
...

如果要在查找中省略命名空间,可以选择使用函数getElementsByTagNameNS(),将通配符'*'作为第一个参数,将您的节点名作为第二个参数,如下所示:

NodeList nodeList = sBody.getElementsByTagNameNS("*", "lastInvoiceDate");

答案 1 :(得分:0)

不需要迭代

SOAPBody sBody = response.getSOAPBody();
NodeList nodeList = sBody.getElementsByTagName("lastInvoiceDate");
// Here you only need to loop nodeList if you have multiple elements with the same tag name
System.out.println(nodeList.item(0).getFirstChild().getTextContent());