我正在搜索轻量级API(最好是单个类)以转换
Map<String,String> map = new HashMap<String,String();
到xml,反之亦然,将XML转换回Map。
例:
Map<String,String> map = new HashMap<String,String(); map.put("name","chris"); map.put("island","faranga"); MagicAPI.toXML(map,"root");
结果:
<root> <name>chris</chris> <island>faranga</island> </root>
然后回来:
Map<String,String> map = MagicAPI.fromXML("...");
我不想使用JAXB或JSON转换API。只需简单的情况,它就不必处理嵌套的地图或属性或其他任何内容。有什么建议么?
编辑:我创建了一个工作副本并粘贴示例。感谢fvu和Michal Bernhard。
下载最新的XStream框架,“仅核心”就足够了。
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);
不需要转换器或其他任何东西。仅xstream-xyzjar就足够了。
XStream!
更新:我按照评论的要求添加了编组部分。
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; } } }