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="" xsi:type="xs:string">Key</key>                     <value xmlns:xs="" 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")

Add Comment
1 Answer(s)

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.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();    = (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; 
Answered on July 17, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.