如何解决如何使用JAXB为XML中的空元素生成自动关闭标签<tag />
jaxb-api
2.3.1
和Java 8的示例代码,其中StringWriter
使用jaxbMarshaller
:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "",propOrder = {
"currencyCode","discountValue","setPrice"
})
@XmlRootElement(name = "countryData")
public class CountryData {
protected String currencyCode;
protected String discountValue = "";
protected String setPrice = "";
// setters and setters
}
当我使用以下命令将实体编组为XML字符串时:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(countryDataObject,sw);
sw.toString();
如何获得空值的预期结果?
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
实际输出:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
解决方法
尽管字符串为空,但它们仍包含非null数据,并生成了结束标记。删除字符串的默认值或将其设置为null
(默认实例字段值):
protected String discountValue;
protected String setPrice;
标签已关闭:
<discountValue/>
<setPrice/>
,
不初始化变量。使用nillable
属性并将其值设置为true
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "",propOrder = { "currencyCode","discountValue","setPrice" })
@XmlRootElement(name = "countryData")
public class CountryData {
@XmlElement(nillable=true)
protected String currencyCode;
@XmlElement(nillable=true)
protected String discountValue;
@XmlElement(nillable=true)
protected String setPrice;
// getters and setters
}
输出
<currencyCode>GBP</currencyCode>
<discountValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<setPrice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。