您可以将 anXmlAdapter
用于此用例:
XmlAdapter (Attribute1Adapter)
您可以利用 JAXB 不会编组 null 属性值这一事实,并使用 anXmlAdapter
来调整要编组为 XML 的值。
import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum16972549.Tag.Foo;
public class Attribute1Adapter extends XmlAdapter<Tag.Foo, Tag.Foo>{
@Override
public Foo unmarshal(Foo v) throws Exception {
return v;
}
@Override
public Foo marshal(Foo v) throws Exception {
if(v == Foo.A) {
return null;
}
return v;
}
}
领域模型(标签)
@XmlJavaTypeAdapter
注解用于XmlAdapter
关联.
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Tag {
enum Foo {A, B};
@XmlAttribute
@XmlJavaTypeAdapter(Attribute1Adapter.class)
private Foo attribute1;
public Foo getAttribute1() {
return attribute1;
}
public void setAttribute1(Foo attribute1) {
this.attribute1 = attribute1;
}
}
演示
下面是一些演示代码,您可以使用它来证明一切正常。
import javax.xml.bind.*;
public class Demo {
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);
}
}
输出
下面是运行演示代码的输出。
A
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag/>
B
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag attribute1="B"/>