如何将此 xml 字符串转换为 java 对象?我尝试了各种各样的东西,也许是 xml 的格式?
我正在使用java 11,通过发送post请求得到了SOAP响应。我希望能够使用 outXML 字符串。我确实有其他的信封,正文,传输响应,outXML类。但我希望至少能够先调用根。
错误:
javax.xml.bind.UnmarshalException: unexpected element
(uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Envelope").
Expected elements are <{http://schemas.xmlsoap.org/soap/envelope/}SOAP-ENV:Envelope>
该 xml 文件
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body SOAP-ENC:encodingStyle="http://schemas.xmlsoap.org/soap/envelope/">
<NS1:TransmitResponse xmlns:NS1="urn:TransmitterIntf-ITransmitter">
<return xsi:type="xsd:int">0</return>
<outXML xsi:type="xsd:string">message</outXML>
</NS1:TransmitResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
信封类:
package com.example
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType(name = "", propOrder = { "body" })
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "SOAP-ENV:Envelope", namespace = "http://schemas.xmlsoap.org/soap/envelope/")
public class Envelope {
@XmlElement(name = "SOAP-ENV:Body")
String body;
// Getter Methods
public String getBody() {
return body;
}
// Setter Methods
public void setBody(String body) {
this.body = body;
}
}
实现:
JAXBContext jaxbContext = JAXBContext.newInstance( Envelope.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringBuffer xmlStr = new StringBuffer( response.getBody() );
Envelope itransmit = (Envelope) jaxbUnmarshaller.unmarshal( new StreamSource( new StringReader(xmlStr.toString())));
System.out.println(itransmit.getBody());
return response.toString();
生成类的最简单方法是使用 wsdl 到 java 插件。例如,如果您使用的是 CXF 和 maven,则可以使用 https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html。这将为您生成 java 代码。
你也可以试试,这是未经测试的代码:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Envelope", namespace = "http://schemas.xmlsoap.org/soap/envelope/")
public class Envelope {
@XmlElement(name = "Body", namespace="http://schemas.xmlsoap.org/soap/envelope/")
String body;
// Getter Methods
public String getBody() {
return body;
}
// Setter Methods
public void setBody(String body) {
this.body = body;
}
}