首页javajaxbJava HTML/XML - 如何强制JAXB解释空元素作为空不空字符串

Java HTML/XML - 如何强制JAXB解释空元素作为空不空字符串

我们想知道如何强制JAXB解释空元素作为空不空字符串。
import java.io.File;

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;
      }
    }

  }
}