【发布时间】:2020-06-28 07:55:22
【问题描述】:
如何将此 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();
【问题讨论】:
标签: java xml spring web-services jaxb