Marshalling java.Util.Properties class into XML using JAXB
I have a use case where I need to Marshal/Unmarshal XML in one particular format using JAXB. By default java.Util.Properties class is Marshalled in below format:
<properties> <entry> <key xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Key</key> <value xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Value</value> </entry> </properties>
But for my use case I want output something like below:
<properties> <property name="Key" value="Value"/> </properties>
This is for simple : properties.put("Key", "Value")
Found a way to do it in JAXB. We can create our custom XmlAdapter to handle the Properties class and have our own custom Attributes name and format. Similar to how we create XmlAdapter for maps See below:
import java.util.*; import java.util.Map.Entry; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlAdapter; public class PropertiesAdapter extends XmlAdapter<PropertiesAdapter.AdaptedProperties, Properties> { public static class AdaptedProperties { @XmlElement(name="property") public List<Property> entry = new ArrayList<Property>(); } public static class Property { @XmlAttribute public String name; @XmlAttribute public String value; } @Override public Properties unmarshal(AdaptedProperties adaptedMap) throws Exception { Properties properties = new Properties(); for(Property entry : adaptedMap.entry) { properties.setProperty(entry.name, entry.value); } return properties; } @Override public AdaptedProperties marshal(Properties properties) throws Exception { AdaptedProperties adaptedMap = new AdaptedProperties(); if (properties==null) return adaptedMap; for(Entry<Object, Object> property : properties.entrySet()) { Property entry = new Property(); entry.name = (String)property.getKey(); entry.value = (String)property.getValue(); adaptedMap.entry.add(entry); } return adaptedMap; } }
Later use this Adapter to set @XmlJavaTypeAdaper annotation in your class as shown below:
@XmlJavaTypeAdapter(PropertiesAdapter.class) @XmlElement protected Properties PIECHART__PROP;