shane shane - 1 year ago 272
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:


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

Answer Source

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

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download