Search code examples
javaxmlxstream

How to convert a Map to an XML


I have a HashMap that I would like convert into an XML file. This tutorial demonstrates how to do this with XStream, and it works wonderfully. However, in my case, I do not need to unmarshall the XML to a Map. Therefore the unmarshal method becomes superflous. Is there another way in XStream to accomplish what I want to do without implementing the unmarshall method. Or is there another friendly Object to XML api that I can use to accomplish this ?


Solution

  • I decided to extends a MapConverter and override its marshal method:

     public static class MapEntryConverter extends MapConverter {
    
    public MapEntryConverter(Mapper mapper) {
        super(mapper);     
    }
    
    public boolean canConvert(Class clazz) {
        return ListMultimap.class.isAssignableFrom(clazz);
    }
    
    public void marshal(Object value, HierarchicalStreamWriter writer,
        MarshallingContext context) {
    
        ListMultimap<String, String> map = (ListMultimap<String, String>) value;
        for (String key : map.keys()) {
        writer.startNode(key);
        writer.setValue(map.get(key).get(0));
        writer.endNode();
        }
    }
    
    
    }
    

    And I use this converter when I marshall my map:

        ListMultimap<String, String> multimap = LinkedListMultimap.create();
    multimap.put("x", "1");
    multimap.put("x", "2");
    multimap.put("y", "3");
    
    XStream xStream = new XStream(new DomDriver());
    xStream.registerConverter(new MapEntryConverter(xStream.getMapper()));
    
    xStream.alias("add", multimap.getClass());
    String xml = xStream.toXML(multimap);
    System.out.println(xml);