I'm using XStream and have a class with a field like the following:
private Map<String, String> data;
I want to generate XML output like this:
<key1>test data</key1>
<key2>test data</key2>
<key3>test data</key3>
So I want the map key to be the element. The mapvalue to be the XML value and I don't want the XML wrapped in an element such as <data></data>
. Can anyone point to sample code that does this, or something similar?
UPDATE
This just a snippet, there is a root element.
UPDATE 2
The custom converter code I posted below almost works. I get a flat structure, but I need to remove the outer element. Any idea on that?
//this is the result need to remove <data>
<data>
<key1>test data</key1>
<key2>test data</key2>
<key3>test data</key3>
</data>
This is the code
public class MapToFlatConverter implements Converter{
public MapToFlatConverter() {
}
@Override
public boolean canConvert(Class type) {
return Map.class.isAssignableFrom(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Map<String, String> map = (Map<String, String>) source;
for (Map.Entry<String, String> entry : map.entrySet()) {
writer.startNode(entry.getKey());
writer.setValue(entry.getValue().toString());
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
//not needed at this time
return null;
}
}