首页 > 解决方案 > 如何生成自闭标签使用 JAXB 处理 XML 中的空元素

问题描述

使用forjaxb-api 2.3.1和 Java 8的示例代码:StringWriterjaxbMarshaller

@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>

标签: javaxmljava-8jaxbmarshalling

解决方案


尽管字符串为空,但它们仍包含非空数据并生成结束标记。删除字符串的默认值或将它们设置为null(默认实例字段值):

protected String discountValue;
protected String setPrice;

标签变为关闭状态:

<discountValue/>
<setPrice/>

推荐阅读