Java HTML / XML How to - Force JAXB to Interpret Empty Element as Null not Empty String








Question

We would like to know how to force JAXB to Interpret Empty Element as Null not Empty String.

Answer

import java.io.File;
/*from   ww  w.jav a  2s.  co m*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Foo.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Foo foo = (Foo) unmarshaller.unmarshal(xml);

    System.out.println(foo.getBar());

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

  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Foo {

    private String bar = "";

    public String getBar() {
      if (bar.length() == 0) {
        return null;
      } else {
        return bar;
      }
    }

    public void setBar(String bar) {
      if (null == bar) {
        this.bar = "";
      } else {
        this.bar = bar;
      }
    }

  }
}

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <bar/>
</foo>