java xml to map_如何将XML转换为java.util.Map,反之亦然

小编典典

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 map = new HashMap();

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 extractedMap = (Map) 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 map = new HashMap();

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;

}

}

}

2020-03-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值