java - 从 xmlsoap 响应中获取值?

标签 java xml soap

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

最佳答案

我建议使用 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();

关于java - 从 xmlsoap 响应中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917870/

相关文章:

web-services - 使用简单的 Camel 代理传播 SOAPFault

java - 如何解决 hibernate 错误: Repeated column in mapping for entity?

java - 传入 BroadcastReceiver 的 onReceive() 的 Context 是什么?

java - 读取和丢弃数据 CSV

sql-server - XQuery T-​​sql 将节点插入到所有元素中

web-services - org.xmlpull.v1.XmlPullParserException : unexpected type (position:END_DOCUMENT null@1:0 in java. io.InputStreamReader@c599f9fd)

java - 如何使用 Jackson 区分 JSONArray 和 JSONObject 与 InputStream?

python - 在 Odoo 中隐藏菜单项?

javascript - 在一个文件中使用 JavaScript 格式化 XML 数据

java - 我应该使用哪种 Java 结构来存储 XML 记录?