A custom XStream converter that can generate a flat XML structure from a list?

I am using XStream and have a class with a field similar to the following:

private Map<String, String> data; 

I want to create XML output as follows:

 <key1>test data</key1> <key2>test data</key2> <key3>test data</key3> 

So, I want the card key to be an element. The map value will be an XML value, and I do not want the XML to be wrapped with an element, such as <data></data> . Can someone please provide some sample code that does this, or something similar?

UPDATE

This is just a fragment, there is a root element.

UPDATE 2

The custom code for the converter, which I posted below, almost works. I get a flat structure, but I need to remove the outer element. Any ideas on this?

 //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; } 

}

+5
source share
1 answer

I was able to get this job. The next SO post is what I ended up doing: a custom XStream converter . I needed to go from ReflectionConverter:

This next article also helped, although when I tried this approach, the context.convertAnother () method did not seem to work. So I switched to the method in the 1st post.

Implicit Xstream Map as Root Element Attributes

0
source

Source: https://habr.com/ru/post/1235124/


All Articles