Search code examples
javaxmljava-8jaxbmarshalling

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


A sample code with jaxb-api 2.3.1 and Java 8 using 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
}

When I marshal the entity to a XML string with:

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(countryDataObject, sw);
sw.toString();

How to get expected result for empty values?

<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>

Actual output:

<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>

Solution

  • don't initialized the variables. use the nillable attribute and set it value to 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
    }
    

    output

    <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"/>