rongmei
rongmei

Reputation: 33

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>

Upvotes: 1

Views: 5356

Answers (3)

n13
n13

Reputation: 31

Just replace them:

.replaceAll("<\w+></\\1>","<$1/>")

Upvotes: 0

Lakshan
Lakshan

Reputation: 1436

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

Upvotes: 1

Nikolas
Nikolas

Reputation: 44486

Although the strings are empty they still contain non-null data and the end tag is generated. Remove the default values of the strings or set them as null (a default instance field value):

protected String discountValue;
protected String setPrice;

The tags become closed:

<discountValue/>
<setPrice/>

Upvotes: 0

Related Questions