2017-02-14 34 views
0

我不知道它是如何可能得到一個SOAP響應體兒的內容時,子標籤,如下所示:獲取SOAP元素在Java中

<sth:x>...</sth:x>

在Oracle文檔我發現如何loop all Elements with a specific name。 但是因此我需要首先創建一個元素來指定我想要搜索的標籤的名稱。

如何創建一個看起來像上面的元素?我知道如何製作這樣的一個:

<sth:id sth="asdf"> 

但是,這並沒有真正的工作。 這是我嘗試閱讀的服務器響應。

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

感謝您的幫助:)

回答

1

試試這個。

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

有兩件重要的事情factory.setNamespaceAware(true); - 打開對xml命名空間的支持。 doc.getDocumentElement().getElementsByTagNameNS("x","id");使用名稱空間URI和元素名稱獲取元素。這裏是<ns5:loginResponse xmlns:ns5="x">命名空間uri的聲明。 x是uri ns5是命名空間。

+0

我試過,但我得到了以下錯誤: 'org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1;在序言中不允許有內容。' 您是否還知道使用SOAP API讀取答案的方法? –

0

我找到了答案:

有問題的元素在另一個SOAPBodyElement中。 所以通過這兩個元素循環給了我正確的值:

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