其他分享
首页 > 其他分享> > Map和xml格式数据互转

Map和xml格式数据互转

作者:互联网

Map和xml格式数据互转

     /**
     * map转xml map中含有根节点的键
     * @param map
     * @throws Exception
     */
    public static String map2xml(Map<String, Object> map) throws Exception  {
        Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
        if(entries.hasNext()){ //获取第一个键创建根节点
            Map.Entry<String, Object> entry = entries.next();
            Document doc = DocumentHelper.createDocument();
            Element root = DocumentHelper.createElement(entry.getKey());
            doc.add(root);
            map2xml((Map)entry.getValue(), root);
            String formatXml = formatXml(doc);
            return formatXml;
        }
        return null;
    }

    /**
     * map转xml
     * @param map
     * @param body xml元素
     * @return
     */
    private static Element map2xml(Map<String, Object> map, Element body) {
        Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            if(key.startsWith("@")){    //属性
                body.addAttribute(key.substring(1, key.length()), value.toString());
            } else if(key.equals("#text")){ //有属性时的文本
                body.setText(value.toString());
            } else {
                if(value instanceof java.util.List ){
                    List list = (List)value;
                    Object obj;
                    for(int i=0; i<list.size(); i++){
                        obj = list.get(i);
                        //list里是map或String,不会存在list里直接是list的,
                        if(obj instanceof java.util.Map){
                            Element subElement = body.addElement(key);
                            map2xml((Map)list.get(i), subElement);
                        } else {
                            body.addElement(key).setText((String)list.get(i));
                        }
                    }
                } else if(value instanceof java.util.Map ){
                    Element subElement = body.addElement(key);
                    map2xml((Map)value, subElement);
                } else {
                    body.addElement(key).setText(value.toString());
                }
            }
            //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        return body;
    }

    /**
     * 格式化输出xml
     * @param document
     */
    public static String formatXml(Document document) throws Exception  {
        // 格式化输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setEncoding("UTF-8");
        StringWriter writer = new StringWriter();
        // 格式化输出流
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        // 将document写入到输出流
        xmlWriter.write(document);
        xmlWriter.close();
        //String xmlStr = writer.toString();
        //org.dom4j.Document document = DocumentHelper.parseText(xmlStr);
        return writer.toString();
    }

    /**
     * 解析xml到map列表
     * @param xml
     * @return
     */
    public static List<Map<String, Object>> xmlStringToMap(String xml){
        List<Map<String, Object>> rslist=new ArrayList<Map<String, Object>>();
        try {
            Document doc = DocumentHelper.parseText(xml);//XML
            // 获取根节点
            Element rootElt = doc.getRootElement();
            List<Element> list=rootElt.elements();
            if(list!=null&&!list.isEmpty()){
                Map<String, Object> resultMap =null;
                for(Element element:list){
                    resultMap = new HashMap<String, Object>();
                    Iterator itersElIterator = element.elementIterator();
                    while(itersElIterator.hasNext()){
                        Element itemEle = (Element) itersElIterator.next();
                        if(StringUtils.isNotBlank(itemEle.getName())){
                            resultMap.put(itemEle.getName(), itemEle.getTextTrim());
                        }
                    }
                    rslist.add(resultMap);
                }
            }
        } catch (Exception e) {
            LOG.error("解析xml字符串失败",e);
        }
        return rslist;
    }

标签:xml,map,Map,Element,entries,互转,entry
来源: https://www.cnblogs.com/coolsheep/p/16179075.html