You can use the XmlAdapter for this use case:
XmlAdapter (attribute 1Adapter)
You could use the fact that JAXB will not march on null attribute values ββand use the XmlAdapter to customize the value that will be bound to 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; } }
Domain Model (tag)
The @XmlJavaTypeAdapter annotation @XmlJavaTypeAdapter used to bind the 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; } }
Demo
Below is some demo code that you can use to prove that everything works.
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); } }
Output
The following is the result of running the demo code.
A <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <tag/> B <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <tag attribute1="B"/>
source share