如何使用 JAXB 为 XML 中的空元素生成自闭合标记 <tag/>

How to generate self-closing tag <tag/> for empty element in XML using JAXB

带有 jaxb-api 2.3.1 和 Java 的示例代码 8 使用 StringWriter for 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>

虽然字符串为空,但它们仍然包含 non-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"/>