Unmarshalling complex XML using JAXB (Moxy)

465 Views Asked by At

I want to unmarshal the following xml using EclipseLink JAXB (MOXy)

<MyObject>
    <Value1>1</Value1>
    <Value2>2</Value2>
    ...
    <ValueN>N</ValueN>
    <Items>
        <Item>
            <Value4>4</Value4>
            ...
            <ValueM>M</ValueM>
        </Item>
        ...
    </Items>
</MyObject>

Where nodes Value1, Value2, etc, are variables.

For this I use the following class

@XmlRootElement(name="MyObject")
public class MyObject {

    public MyObject() {
        this.items = new ArrayList<Item>();
    }

    @XmlPath(".")
    @XmlJavaTypeAdapter(MyMapAdapter.class)
    private Map<String, String> map = new HashMap<String, String>();

    private List<Item> items;

    public List<Item> getItems() {
        return items;
    }

    @XmlElementWrapper(name="Items")
    @XmlElement(name="Item")
    public void setItems(List<Item> items) {
        this.items = items;
    }
}

Where in MyMapAdapter I get a list of Value nodes and their "values". If I remove the "map" property, then the values of the list are loaded correctly.

This is MyMapAdapter:

public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, String>> {

public static class AdaptedMap {
    @XmlVariableNode("key")
    List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}

public static class AdaptedEntry {
    @XmlTransient
    public String key;

    @XmlValue
    public String value;
}

@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
    AdaptedMap adaptedMap = new AdaptedMap();

    for(Entry<String, String> entry : map.entrySet()) {
        AdaptedEntry adaptedEntry = new AdaptedEntry();
        adaptedEntry.key = entry.getKey();
        adaptedEntry.value = entry.getValue();
        adaptedMap.entries.add(adaptedEntry);
    }

    return adaptedMap;
}

@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
    List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
    Map<String, String> map = new HashMap<String, String>(adaptedEntries.size());

    for(AdaptedEntry adaptedEntry : adaptedEntries) {
        if(!"Items".equals(adaptedEntry.key)){
            map.put(adaptedEntry.key, adaptedEntry.value);
        }
    }

    return map;
}

}

What am I doing wrong? How this can be done?

Any help will be greatly appriciated

0

There are 0 best solutions below