I have a XML file like the following:
<root>
<item>
<id>my id</id>
<type>my type</id>
<key1>value1</key1>
<key2>value1</key2>
<key3>value1</key3>
</item>
<item>
<id>my id</id>
<type>my type</type>
<other-key1>value1</other-key1>
<other-key2>value1</other-key2>
</item>
(...)
</root>
And I want to parse the XML on a class like this:
public class Item {
private String id;
private String type;
private Map<String, String> values;
}
Where the id node and the type node are mapped to the attributes with the same name and everyting else inside a item are added to a map.
I have tried write a class with the annotations XmlJavaTypeAdapter and XmlAnyElement but this does not work how I expect:
(...)
public class Item {
@XmlElement
private String id;
@XmlElement
private String type;
@XmlAnyElement
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String, String> values;
}
public class MapAdapter extends XmlAdapter<Object, Map<String, String>> {
@Override
public Object marshal(Map<String, String> v) throws Exception {
}
@Override
public Map<String, String> unmarshal(Object v) throws Exception {
// v is a node instead an array of nodes.
// I want to get an array of nodes to convert them to a map.
//
// eg:
//
// key1 -> value1
// key2 -> value2
// key3 -> value3
//
}
Any idea how I can get this?
UPDATE
A clarification of my question:
My problem is that the elements that I want to unmarshal within the map are not inside a wrapper and they are mixed with another elements at the same level.
I tried to use the XmlAnyElement and XmlJavaTypeAdapter to get a map of all the remaining elements. However there is an implicit order on these annotations and what I get is a collection of elements parsed with the adapter:
XmlAnyElement finds each remaining element, parse it with the adapter and add the result to a collection.
Is there any way to reverse this?
I want to get a collection of all the remaining elements and then parse the collection with the XmlAdapter to get a map.