简体   繁体   中英

XStream custom converter that can generate flat XML structure from List?

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

}

I was able to get this working. The following SO post is what I ultimately did: custom converter in XStream . I needed to extend from the ReflectionConverter:

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

Xstream Implicit Map As Attributes to Root Element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM