简体   繁体   English

将 XML 文件中的 SOAP 响应解析为对象

[英]Parse SOAP response from XML file into object

I have a project with a working SOAP integration and I need to write some tests.我有一个可以运行 SOAP 集成的项目,我需要编写一些测试。

To avoid making making web service calls during tests, I saved some SOAP responses into XML files, but I don't know how to turn these XML into the appropriate objects.为了避免在测试期间进行 Web 服务调用,我将一些 SOAP 响应保存到 XML 文件中,但我不知道如何将这些 XML 转换为适当的对象。

I've tried using JAXBContext / Unmarshaller , but I get the error expected elements are (None) , which I believe is related to the fact that the class associated with the XML response doesn't have a @XmlRootElement annotation (and I can't change this).我试过使用JAXBContext / Unmarshaller ,但我得到错误expected elements are (None) ,我认为这与与 XML 响应关联的类没有@XmlRootElement注释(我可以) t 改变这个)。

This question is very similar to mine, but the current answer doesn't really specify how to get the final object from the response. 这个问题与我的非常相似,但当前的答案并没有真正指定如何从响应中获取最终对象。

It's also not clear to me if I have to leave the SOAP-specific tags or if it's easier to strip them and treat the file as a normal XML.我也不清楚是否必须保留特定于 SOAP 的标记,或者是否更容易剥离它们并将文件视为普通的 XML。

After seeing this answer I got it working.看到这个答案后,我得到了它的工作。

The problem was the missing @XmlRootElement as expected and in order to make it work the 2-parameter version of unmarshall() should be used as below (code from the other question):问题是缺少@XmlRootElement ,为了使其工作,应该使用unmarshall()的 2 参数版本,如下所示(来自另一个问题的代码):

String pathname = "file.xml";
InputStream stream = new FileInputStream(pathname); 
JAXBContext jaxbContext = JAXBContext.newInstance(UserType.class); 
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
XMLInputFactory factory = XMLInputFactory.newInstance(); 
XMLEventReader someSource = factory.createXMLEventReader(stream); 
JAXBElement<UserType> userElement = jaxbUnmarshaller.unmarshal(someSource, UserType.class); UserType user = userElement.getValue();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM