5

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

}

Mr Smith
  • 3,318
  • 9
  • 47
  • 85
  • 1
    Valid XML must not have multiple root elements. – dummy Nov 03 '15 at 14:05
  • this is just a snippet. There is a root element. I just want the list elements to appear flat. – Mr Smith Nov 03 '15 at 14:08
  • what is with the close votes? This seems like a question that SO was created for. – Mr Smith Nov 03 '15 at 14:55
  • Maybe you could show us some code, the current output and a more complete expected output. (For the record: I did not vote to close this, just trying to help). – dummy Nov 03 '15 at 14:59
  • How would you unmarshal it without the containing element? – biziclop Nov 04 '15 at 18:01
  • In my case I don't need to unmarshal it. I'm serializing some Java objects to XML & sending it to an external system. The external system doesn't return any XML that I need to deserialize – Mr Smith Nov 04 '15 at 19:04

1 Answers1

0

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

Community
  • 1
  • 1
Mr Smith
  • 3,318
  • 9
  • 47
  • 85