如何使用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"/>