Is there any way to make JAXB not save fields which values are the default values specified in the @Element annotations, and then make set the value to it when loading elements from XML that are null or empties? An example:
class Example
{
@XmlElement(defaultValue="default1")
String prop1;
}
Example example = new Example();
example.setProp1("default1");
jaxbMarshaller.marshal(example, aFile);
Should generate:
<example/>
And when loading
Example example = (Example) jaxbUnMarshaller.unmarshal(aFile);
assertTrue(example.getProp1().equals("default1"));
I am trying to do this in order to generate a clean XML configuration file, and make it better readable and smaller size.
Regars and thanks in advance.
You could do something like the following by leveraging
XmlAccessorType(XmlAccessType.FIELD)
and putting logic in the get/set methods:Example
Demo
Output
For More Information
For a programmatic solution, there's also good old Apache commons XmlSchema and you can check against the default value with XmlSchemaElement.getDefaultValue()
So with something like
you should be able to do what you need. Haven't tried it out in the end, because I needed a more direct solution, but I hope that helps.