shane shane - 5 months ago 50
Java Question

Dynamic tag names with JAXB

I am using Jersey and JAXB to build a simple RESTful webservice
I have a HashMap of 'String' to 'Integer':

2010-04 -> 24
2010-05 -> 45


I need to generate an XML response which looks like this:

<map>
<2010-04>24</2010-04>
<2010-05>45</2010-05>
</map>


What is the best way to generate dynamic tag names with JAXB?

Answer

You can use an @XmlAnyElement-annotated property and return the elements as JAXBElements:

private Map<String, Integer> months = ...;

@XmlAnyElement
public List<JAXBElement<Integer>> getMonths() {
    List<JAXBElement<Integer>> elements = new ArrayList<JAXBElement<Integer>>();
    for (Map.Entry<String, Integer> month: months.entrySet()) 
        elements.add(new JAXBElement(new QName(month.getKey()), 
                                     Integer.class, month.getValue()));
    return elements;
}

This approach is ugly, but not uglier than the XML it produces.