'How to not show empty lists in JAXB XML marshalling?

Hi I am using JAXB (JAVA) to marshal XML.

I have some XmlList elements that are sometimes size is zero.

Since it constructs actual array list when getter is called,

the output always displays empty elements like

<aa></aa>

is there anyway to eliminate these "empty" elements?

Thanks.



Solution 1:[1]

public void representingNullAndEmptyCollections() throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);

    Root root = new Root();

    root.nullCollection = null;

    root.emptyCollection = new ArrayList<String>();// Shows a Empty Element

    root.populatedCollection = new ArrayList<String>();
    root.populatedCollection.add("foo");
    root.populatedCollection.add("bar");

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
}

Solution 2:[2]

Generally null fields are not rendered by JAXB. The trick is to use a special getter.

It is commonly as simple as:

public List<String> getStuff() {
    return stuff.isEmpty() ? null : stuff;
}

Solution 3:[3]

After tripping over this same problem, I have come up with something that can be made to work with some re-coding effort. First step is to set the Jaxb property:

generateIsSetMethod="true"

for the "collection" element. There are multiple ways to do this either inside the schema itself, or by using an external set of properties. My external file looks like:

<jxb:bindings version="1.0"
          xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
          xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <jxb:bindings schemaLocation="umdb.xsd" node="/xs:schema">
    <jxb:bindings node="//xs:complexType[@name='EnumerationListType']">
      <jxb:bindings node=".//xs:element[@name='Enum']">
        <jxb:property generateIsSetMethod="true"/>
      </jxb:bindings>
    </jxb:bindings>
  </jxb:bindings>
</jxb:bindings>

This produces methods isSetEnum() and unsetEnum() in addition to the getEnum() method that replaces a null list with an new empty one.

That gives you the choice of the "isSet" method before calling the "get" method, or checking if the list is empty and calling the "unset" method before marshalling. I agree that this is not a great solution, but it does provide one.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjit Kumar Mishra
Solution 2 OldCurmudgeon
Solution 3 FLB