Map与XML的相互转换

工具类:

public class XmlUtils {

    /**
     * 功能描述: Map 转 Xml字符串
     */
    public static String map2Xml(Map paras) {
        SortedMap paraMap = new TreeMap();
        paraMap.putAll(paras);
        String xmlStr = "";
        Set es = paraMap.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            xmlStr += "<" + k + ">" + v + "";
        }
        xmlStr += "";
        return xmlStr;
    }

    /**
     * 功能描述: XML字符串 转 Map
     */
    public static Map xml2Map(String xmlStr) throws Exception {
        // TODO
        Map rtnMap = new HashMap();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xmlStr);//通过DOM4J解析XML字符串
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //得到根节点
        Element root = doc.getRootElement();
        // 获取所有子元素
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element el = (Element) i.next();
            rtnMap.put(el.getName(), el.getText());

        }
        return rtnMap;
    }
 }

测试类:

public class XMLTest2 {
    public Map init(){
        HashMap map = new HashMap<>();
        map.put("parm1","value1");
        map.put("parm2","value2");
        map.put("parm3","value3");
        map.put("parm4","value4");
        map.put("parm5","value5");
        return map;
    }
    @Test
    public void MapAndXml() throws Exception {
        Map map = init();
        String xml = XmlUtils.map2Xml(map);
        System.out.println(xml);
        Map xml2Map = XmlUtils.xml2Map(xml);
        System.out.println(xml2Map);
    }
}

输出:


  value1
  value2
  value3
  value4
  value5



{parm4=value4, parm5=value5, parm1=value1, parm2=value2, parm3=value3}

你可能感兴趣的:(XML)