问题描述
编辑:我已重新设置问题的格式,以期使我的意图更加清楚。
我正在尝试使用JAXB marshaller将Java对象映射到XML,以创建针对供应商SOAP服务的肥皂请求。
我有几个元素需要在请求中显示,即使它们为空或为空。
我在pom.xml中使用目标为jaxws-maven-plugin
的{{1}}插件从WSDL文件生成源。
wsimport
我从此处阅读并理解[https://stackoverflow.com/questions/11215485/jax-ws-to-remove-empty-tags-from-request-xml],其中包含{{1 }}类型,可以通过将空字符串<plugin>
<groupId>com.helger.maven</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlFiles>
<wsdlFile>${project.basedir}/src/wsdl/sample/SomeSoapService.wsdl</wsdlFile>
</wsdlFiles>
</configuration>
<id>wsimport-generate-cbs</id>
<phase>generate-sources</phase>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>webservices-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<configuration>
<sourceDestDir>${project.build.directory}/generated-sources/jaxws-wsimport</sourceDestDir>
<xnocompile>true</xnocompile>
<xadditionalHeaders>true</xadditionalHeaders>
<verbose>true</verbose>
<extension>true</extension>
</configuration>
设置为其值来生成一个空标记。但这不能在类型分别为xs:string
的元素上进行,例如""
。如果将它们的值设置为null,则在编组过程中将不会生成元素。就像其他人指出的那样,可以通过在xs:dateTime,xs:boolean,xs:integer
上添加XMLGregorianCalendar,BigInteger,Boolean
来实现,但这将需要更改为生成的源,在下一个版本中它将被覆盖,除非我在第一次构建。
我目前的解决方法是,将WSDL文件中需要显示在请求中的那些特定元素的类型更改为nillable=true
,并将空字符串传递给它们相应的java对象字段。
我的问题是,是否有可能在WSDL方面进行更改以触发jaxws:wsimport在生成的@XmlElement
字段中添加xs:string
?我更喜欢更改WSDL文件而不是生成源的原因是
以下是代码的简化版本。
首先,我有这个为complexType Currency生成的java类。
nillable=true
我将这些字段设置为null,因为它们不存在。
@XmlElement
// Generated
@XmlAccessorType(XmlAccesstype.FIELD)
@XmlType(name = "currency",propOrder = {
"crossCurrency","amount"
})
public class Currency {
@XmlElement(required = true)
protected Boolean crossCurrency;
@XmlElement(required = true)
protected BigDecimal amount;
}
解决方法
将nillable
属性与@XmlElement
一起使用并将其值设置为true
Currency.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "currency",propOrder = {
"isoCurrencyCode","amount"
})
public class Currency {
@XmlElement(required = true,nillable=true)
protected Boolean crossCurrency;
@XmlElement(required = true,nillable=true)
protected BigDecimal amount;
}
输出
<typ:Currency>
<typ:crossCurrency xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<typ:amount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</typ:Currency>
WSDL
在每个请求的元素中添加nillable
属性并将其值设置为true
,如下例所示,
<xsd:element name="Currency" nillable="true" ... />