2014-11-13 155 views
0

您好我有把這個SOAP請求的java程序:從xml soap響應中獲取值?

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
        xmlns:gs="http://talosdigital.com/buyer"> 
    <soapenv:Header/> 
    <soapenv:Body> 
     <gs:createBuyerRequest> 
     <gs:name>Carlos</gs:name> 
     <gs:lastname>henao</gs:lastname> 
     </gs:createBuyerRequest> 
    </soapenv:Body> 
</soapenv:Envelope> 

,我得到這樣的響應:

SOAPMessage soapResponse = soapConection.call(soapMessage, Properties.URL); 
soapResponse.writeTo(System.out); 

當我打印顯示此:

<SOAP-ENV:Envelope> 
    <SOAP-ENV:Header /> 
    <SOAP-ENV:Body> 
     <ns2:createBuyerResponse> 
      <ns2:id>8</ns2:id> 
      <ns2:response>Buyer Created</ns2:response> 
     </ns2:createBuyerResponse> 
</SOAP-ENV:Body> 
</SOAP-ENV:Envelope> 

我怎樣才能在java中獲得id值(是一個整數值)。

回答

1

我會建議使用JAXB編組爲Java對象的響應,那麼你可以做任何你想要的響應

創建響應JAXB對象:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "", propOrder = { 
    "id", 
    "response" 
}) 
@XmlRootElement(name = "createBuyerResponse") 
public class BuyerResponse{ 

    @XmlElement(name = "id", required = true) 
    protected int id; 

    @XmlElement(name = "response", required = true) 
    protected String response; 

    public int getId() { 
     return this.id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getResponse() { 
     return this.response; 
    } 

    public void setResponse(String response) { 
     this.response = response; 
    } 
} 

和那麼馬歇爾你對物體的反應

JAXBContext jc = JAXBContext.newInstance(BuyerResponse.class); 
    Unmarshaller unmarshaller = jc.createUnmarshaller(); 

    JAXBElement<BuyerResponse> je = unmarshaller.unmarshal(soapResponse.getSOAPBody().extractContentAsDocument(), BuyerResponse.class); 

    BuyerResponse value = je.getValue();