如何将XML转换为java

如何将XML转换为java

本文介绍了如何将XML转换为java.util.Map,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索轻量级API(最好是单个类)以转换

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

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

转换为XML,反之亦然,将XML转换回 Map< String,String> .

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

示例:

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 .只需简单的情况,就不必照顾嵌套的地图或属性或其他任何东西.有什么建议吗?

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?

我创建了工作副本&粘贴样品.感谢 fvu 米哈尔·伯恩哈德(Michal Bernhard).

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

下载最新的XStream框架,仅内核"就足够了.

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

不需要转换器或其他任何东西.只是 xstream-xyzjar 就足够了.

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

推荐答案

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

    }

}

这篇关于如何将XML转换为java.util.Map,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!