hnnn
hnnn

Reputation: 504

JAXB, use xml attribute as a key in hashmap

i have a very simple xml

<List>
   <Item name="somename">
        .....
   </Item>
   <Item name="somename2">
   ....

in my java object i want to use name attribute as a key in a hashmap. Is it possible with jaxb? Something like

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "List")
public class MyList {
    private HashMap<String,Item> map;
}

Upvotes: 2

Views: 1257

Answers (1)

M F
M F

Reputation: 323

A little late and I havn't tried it myself yet but one could try the following:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "List")
public class MyList {
    private HashMap<String, Item> map;

    @XmlElement(name = "entry")
    public MapEntry[] getMap() {
        List<MapEntry> list = new ArrayList<MapEntry>();
        for (Entry<String, Item> entry : map.entrySet()) {
            MapEntry mapEntry = new MapEntry();
            mapEntry.key = entry.getKey();
            mapEntry.value = entry.getValue();
            list.add(mapEntry);
        }

        return list.toArray(new MapEntry[list.size()]);
    }

    public void setMap(MapEntry[] arr) {
        for(MapEntry entry : arr) {
            this.map.put(entry.key, entry.value);
        }
    }

    public static class MapEntry {
        @XmlAttribute
        public String key;
        @XmlValue
        public Item value;
    }
}

Upvotes: 1

Related Questions