通过 jaxb 插件从 wsdl 生成对象
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "WebAuthenticationCredential", propOrder = {
"key",
"password"
})
public class WebAuthenticationCredential {
@XmlElement(name = "Key", required = true)
protected String key;
@XmlElement(name = "Password", required = true)
protected String password;
方法:
public RateReply getRates(
Request sRequest) {
try {
ObjectFactory objectFactory = new ObjectFactory();
JAXBElement<WebAuthenticationCredential> soapRateRequest =
objectFactory.createRateRequest(sRequest);
XmlMapper xmlMapper = new XmlMapper();
String xmlContent = xmlMapper.writeValueAsString(soapRateRequest);
logger.info(xmlContent); // check below the response
Reply rReply = (Reply) JAXBIntrospector
.getValue(WebServiceTemplate.marshalSendAndReceive(serviceUri, soapRateRequest));
handleErrors(rateReply);
return rateReply;
} catch (SoapFaultClientException e) {
logger.error("Caught exception rates", e);
throw new Exception("Failed calling service ", null);
}
}
来自 JAXB 生成的 ObjectFactory 类的 createRequest 方法:
/**
* Create an instance of {@link JAXBElement }{@code <}{@link RateRequest }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedex.com/ws/rate/v14", name = "PreAuthorizedRateRequest")
public JAXBElement<RateRequest> createPreAuthorizedRateRequest(RateRequest value) {
return new JAXBElement<RateRequest>(_PreAuthorizedRateRequest_QNAME, RateRequest.class, null, value);
xmlContent 的记录器信息(使用驼峰式大小写元素打印)为
<JAXBElement>
<name>PreRequest</name>
<declaredType>Request</declaredType>
<scope>javax.xml.bind.JAXBElement$GlobalScope</scope>
<value>
<webAuthenticationDetail>
<key>test</key>
<password>password</password>
</webAuthenticationDetail>
</value>
</JAXBElement>
预期输出:里面的所有元素都应该是帕斯卡大小写(WebAuthenticationDetail、Key、Password),JAXB可能吗?
<JAXBElement>
<name>PreRequest</name>
<declaredType>Request</declaredType>
<scope>javax.xml.bind.JAXBElement$GlobalScope</scope>
<value>
<WebAuthenticationDetail>
<Key>test</Key>
<Password>password</Password>
</WebAuthenticationDetail>
</value>
</JAXBElement>
最佳答案
默认情况下,XmlMapper 无法识别 JAXB 注释。要启用它们,您需要注册模块JaxbAnnotationModule。
示例:
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.registerModule(new JaxbAnnotationModule());
关于java - JAXB java对象到xml,创建Pascal Case XML元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047174/