I am having trouble customizing my JAXB Marshaller. I have my marshaller code:
public void marshaller(AddressMap addMap, File file) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(AddressMap.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(addMap, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
The output looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ObjectMap>
<Prop> Indiana</Prop>
<Prop1>39.0</Prop1>
<Prop2>-85.0</Prop2>
<Prop3> United States</Prop3>
<Prop4> Hueseman Rd</Prop4>
<Prop5> 8540-8704</Prop5>
<Prop6> 47001</Prop6>
</ObjectMap>
Instead, I need it to look like this:
<bean class="classname">
<property name="PropName" value="object value" />
<property name="PropName1" value="object value" />
<property name="PropName2" value="object value" />
<property name="PropName3" value="object value" />
<property name="PropName4" value="object value" />
<property name="PropName5" value="object value" />
<property name="PropName6" value="object value" />
</bean>
Note: I’m the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You could use MOXy’s
@XmlDesciminatorNodeand@XmlPathextensions to map this use case. Below is an example based on what I assume your object model looks like.ObjectMap
The
@XmlDescriminatorNodeannotation allows you to specify that you want a specific XML attribute to serve as the inheritance indicator.AddressMap
The
@XmlDescriminatorValueannotation is used to specify the value on the descriminator node that relates to the instance class. In this class we also use the@XmlPathannotation to indicate whichpropertyelement we wish to map to based on the value of itsnameattribute.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.Demo
The following demo code will convert the XML message to an instance of
AddressMapand then back to XML.input.xml/Output
For More Information