public class Person {
public String name; ...
}
When I marhsal I want to get a Name node with value attribute
<name value="arahant" />
instead of :
<name>arahant</name>
How can I achieve this? I tried looking at the XmlElementWrapper but that is allowed only for collections. Would I need to write custom code for this?
There are a couple of options available to you to support this use case.
OPTION #1 –
XmlAdapterANY JAXB (JSR-222) IMPLEMENTATIONThis approach will work with any JAXB (JSR-222) compliant implementation.
ValueAdapter
An
XmlAdapterallows you to marshal one object as if it were another object. In ourXmlAdapterwe will convert theStringvalue to/from an object that has one property mapped with@XmlAttribute.Person
The
@XmlJavaTypeAdapterannotation is used to specify that theXmlAdaptershould be used with a field or property.OPTION #2 – EclipseLink JAXB (MOXy)
I’m the EclipseLink JAXB (MOXy) lead and we offer the
@XmlPathextension which allows you to easily do path based mapping.Person
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called
jaxb.propertiesin the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).DEMO CODE
The following demo code can be used with either option:
Demo
input.xml/Output