Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert XML to java.util.Map and vice versa?

Tags:

java

xml

I'm searching a lightweight API (preferable single class) to convert a

Map<String,String> map = new HashMap<String,String(); 

to XML and, vice versa, convert the XML back to a Map<String,String>.

example:

Map<String,String> map = new HashMap<String,String(); map.put("name","chris"); map.put("island","faranga");  MagicAPI.toXML(map,"root"); 

result:

<root>   <name>chris</chris>   <island>faranga</island> </root> 

and back:

Map<String,String> map = MagicAPI.fromXML("..."); 

I don't want to use JAXB or JSON conversion API. It doesn't have to take care of nested maps or attributes or anything else, just that simple case. Any suggestions?


I created a working copy & paste sample. Thanks to fvu and Michal Bernhard.

Download latest XStream framework, 'core only' is enough.

Map<String,Object> map = new HashMap<String,Object>(); map.put("name","chris"); map.put("island","faranga");  // convert to XML XStream xStream = new XStream(new DomDriver()); xStream.alias("map", java.util.Map.class); String xml = xStream.toXML(map);  // from XML, convert back to map Map<String,Object> map2 = (Map<String,Object>) xStream.fromXML(xml); 

No converters or anything else is required. Just the xstream-x.y.z.jar is enough.

like image 514
Chris Avatar asked Oct 08 '09 11:10

Chris


People also ask

How to convert XML data to map in java?

Map. class); String xml = xStream. toXML(map); // from XML, convert back to map Map<String,Object> map2 = (Map<String,Object>) xStream. fromXML(xml);


2 Answers

XStream!

Updated: I added unmarshal part as requested in comments..

import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter;  import java.util.AbstractMap; import java.util.HashMap; import java.util.Map;  public class Test {      public static void main(String[] args) {          Map<String,String> map = new HashMap<String,String>();         map.put("name","chris");         map.put("island","faranga");          XStream magicApi = new XStream();         magicApi.registerConverter(new MapEntryConverter());         magicApi.alias("root", Map.class);          String xml = magicApi.toXML(map);         System.out.println("Result of tweaked XStream toXml()");         System.out.println(xml);          Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);         assert extractedMap.get("name").equals("chris");         assert extractedMap.get("island").equals("faranga");      }      public static class MapEntryConverter implements Converter {          public boolean canConvert(Class clazz) {             return AbstractMap.class.isAssignableFrom(clazz);         }          public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {              AbstractMap map = (AbstractMap) value;             for (Object obj : map.entrySet()) {                 Map.Entry entry = (Map.Entry) obj;                 writer.startNode(entry.getKey().toString());                 Object val = entry.getValue();                 if ( null != val ) {                     writer.setValue(val.toString());                 }                 writer.endNode();             }          }          public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {              Map<String, String> map = new HashMap<String, String>();              while(reader.hasMoreChildren()) {                 reader.moveDown();                  String key = reader.getNodeName(); // nodeName aka element's name                 String value = reader.getValue();                 map.put(key, value);                  reader.moveUp();             }              return map;         }      }  } 
like image 185
Michal Bernhard Avatar answered Oct 08 '22 03:10

Michal Bernhard


Here the converter for XStream including unmarshall

public class MapEntryConverter implements Converter{ public boolean canConvert(Class clazz) {     return AbstractMap.class.isAssignableFrom(clazz); }  public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {     AbstractMap<String,String> map = (AbstractMap<String,String>) value;     for (Entry<String,String> entry : map.entrySet()) {         writer.startNode(entry.getKey().toString());         writer.setValue(entry.getValue().toString());         writer.endNode();     } }  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {     Map<String, String> map = new HashMap<String, String>();      while(reader.hasMoreChildren()) {         reader.moveDown();         map.put(reader.getNodeName(), reader.getValue());         reader.moveUp();     }     return map; } 
like image 41
Vikas Gujjar Avatar answered Oct 08 '22 03:10

Vikas Gujjar