【问题标题】:Get a value from xml soap response?从 xml 肥皂响应中获取值?
【发布时间】:2014-11-13 20:33:42
【问题描述】:

您好,我有一个发送此 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 值(是一个整数值)。

【问题讨论】:

    标签: java xml soap


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-08-18
        • 2017-11-09
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-21
        相关资源
        最近更新 更多