从xml soap响应中获取值?

时间:2014-11-13 20:33:42

标签: java xml soap

您好我有一个发送此肥皂请求的java程序:

<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值(是一个整数值)。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

获得响应后,您可以使用SAX或DOM Parser API来解析XML元素并使用构造函数(Getter和Setter)存储值。请在线查看SAX Parser API。这是链接:http://www.javacodegeeks.com/2012/01/xml-parsing-using-saxparser-with.html

注意:从流中获取响应,然后解析并存储值。