I have a Person class (annotated with @XmlRootElement) in Java with two properties (name, birthday), which I need to marshal in two different ways, generating two different XML files.
In the first file, the Person object should contain only the name property:
<Person>
<name>John Doe</name>
</Person>
In the second file, the Person object should contain all properties.
<Person>
<name>John Doe</name>
<birthday>1980-01-01</birthday>
</Person>
Is there a way to achieve this with JAXB?
Regards,
Jochen
Note: I’m the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can use JAXB annotations to provide one representation, and leverage MOXy’s external binding document to provide alternate representations.
Use Case 1 – Minor Differences Between Representations
By default MOXy’s external mapping document is used to override metadata provided by annotations. This allows you to tweak the representation between versions. Below is a link to an answer I gave with a detailed example:
Use Case 2 – Major Differences Between Representations
MOXy’s external mapping document can also be used to override all the annotations. This is useful when the representations are not related. Below is a link to an example where I map the same object model to both the Google and Yahoo weather services:
For More Information