把xml转化为soapmessage_将Soap XML响应转换为对象

本文介绍如何将XML转换为SOAP消息,并利用JAXB将SOAP XML响应解析为Java对象。通过创建XMLStreamReader并使用JAXBContext实例进行反序列化,实现了将XML数据绑定到LoginResult类的对象。
摘要由CSDN通过智能技术生成

小编典典

您可以使用此代码检索POJO,还可以将@XmlRootElement作为标头添加到POJO。

(我没有测试下面的代码)

XMLInputFactory xif = XMLInputFactory.newFactory();

XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));

xsr.nextTag(); // Advance to Envelope tag

xsr.nextTag(); // Advance to Body tag

xsr.nextTag();

xsr.nextTag();

Transformer transformer = TransformerFactory.newInstance().newTransformer();

StringWriter stringWriter = new StringWriter();

transformer.transform(new StAXSource(xsr), new StreamResult(stringWriter));

StringReader sr = new StringReader(stringWriter.toString());

JAXBContext jaxbContext = JAXBContext.newInstance(LoginResult.class);

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

LoginResult loginResult = (LoginResult) unmarshaller.unmarshal(sr);

编辑:

我为您找到了解决方案:

@XmlRootElement(name = "LoginResult", namespace = "http://test.org/ADMail_Service")

@XmlAccessorType(XmlAccessType.FIELD)

public class LoginResult {

@XmlElement(name = "ErrorMessage", namespace = "http://test.org/ADMail_Service")

private String errorMessage;

@XmlElement(name = "Status", namespace = "http://test.org/ADMail_Service")

private String status;

public String getErrorMessage() {

return errorMessage;

}

public void setErrorMessage(String errorMessage) {

this.errorMessage = errorMessage;

}

public String getStatus() {

return status;

}

public void setStatus(String status) {

this.status = status;

}

}

public static void main(String[] args) {

try {

XMLInputFactory xif = XMLInputFactory.newFactory();

XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));

xsr.nextTag(); // Advance to Envelope tag

xsr.nextTag(); // Advance to Body tag

xsr.nextTag();

xsr.nextTag();

JAXBContext jc = JAXBContext.newInstance(LoginResult.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();

JAXBElement je = unmarshaller.unmarshal(xsr, LoginResult.class);

System.out.println(je.getName());

System.out.println(je.getValue());

System.out.println(je.getValue().getErrorMessage());

} catch (XMLStreamException e) {

e.printStackTrace();

} catch (JAXBException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

2020-10-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值