首页javajaxbJava HTML/XML - 如何指定JAXB应该只打印属性,如果它没有特定的值

Java HTML/XML - 如何指定JAXB应该只打印属性,如果它没有特定的值

我们想知道如何指定JAXB应该只打印属性,如果它没有特定的值。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Tag {

  private static Foo ATTRIBUTE1_DEFAULT = Foo.A;

  enum Foo {
    A, B
  };

  @XmlAttribute
  private Foo attribute1;

  public Foo getAttribute1() {
    if (null == attribute1) {
      return ATTRIBUTE1_DEFAULT;
    }
    return attribute1;
  }

  public void setAttribute1(Foo attribute1) {
    if (ATTRIBUTE1_DEFAULT == attribute1) {
      this.attribute1 = null;
    } else {
      this.attribute1 = attribute1;
    }
  }

}

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Tag.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Tag tag = new Tag();
    tag.setAttribute1(Tag.Foo.A);
    System.out.println(tag.getAttribute1());
    marshaller.marshal(tag, System.out);

    tag.setAttribute1(Tag.Foo.B);
    System.out.println(tag.getAttribute1());
    marshaller.marshal(tag, System.out);
  }

}