java解析xml转为Map

之前开发过一个解析多层级xml文件的工具类,后来处理的时候发现,这种方式得到的map或json集合多一个key标签,在解析的时候会比较麻烦,于是根据需要在原有方法的基础上写出了另外的处理方法,总结记录如下:

1、单节点单层级、单节点多层级xml转map

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 功能:XML解析工具类
 * @author lmb 
 * @version 1.0
 * @date 2017-6-5
 */
public class ParseXMLUtils {

    /**
     * 将Document对象转为Map(String→Document→Map)
     * @param Document
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Map Dom2Map(Document doc){  
        Map map = new HashMap();  
        if(doc == null)  
            return map;  
        Element root = doc.getRootElement();  
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {  
            Element e = (Element) iterator.next();  
            //System.out.println(e.getName());  
            List list = e.elements();  
            if(list.size() > 0){  
                map.put(e.getName(), Dom2Map(e));  
            }else  
                map.put(e.getName(), e.getText());  
        }  
        return map;  
    }

    /**
     * 将Element对象转为Map(String→Document→Element→Map)
     * @param Element
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map Dom2Map(Element e){  
        Map map = new HashMap();  
        List list = e.elements();  
        if(list.size() > 0){  
            for (int i = 0;i < list.size(); i++) {  
                Element iter = (Element) list.get(i);  
                List mapList = new ArrayList();  
                if(iter.elements().size() > 0){  
                    Map m = Dom2Map(iter);  
                    if(map.get(iter.getName()) != null){  
                        Object obj = map.get(iter.getName());  
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){  
                            mapList = new ArrayList();  
                            mapList.add(obj);  
                            mapList.add(m); 
                        }  
                        if(obj.getClass().getName().equals("java.util.ArrayList")){  
                            mapList = (List) obj;  
                            mapList.add(m);
                        }  
                        map.put(iter.getName(), mapList); 
                    }else  
                        map.put(iter.getName(), m);  
                }  
                else{  
                    if(map.get(iter.getName()) != null){  
                        Object obj = map.get(iter.getName()); 
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){  
                            mapList = new ArrayList();  
                            mapList.add(obj);  
                            mapList.add(iter.getText());  
                        }  
                        if(obj.getClass().getName().equals("java.util.ArrayList")){  
                            mapList = (List) obj;  
                            mapList.add(iter.getText());  
                        }  
                        map.put(iter.getName(), mapList); 
                    }else  
                        map.put(iter.getName(), iter.getText());//公共map resultCode=0
                }  
            }  
        }else  
            map.put(e.getName(), e.getText());  
        return map;  
    }  

    public static void main(String[] args) {   
        String str1 = "
" + " 2" + " EUR" + " 11" + " tom" + " sss" + "
"
; String str2 = "" + "
" + " 2" + " 11" + " tom" + " sss" + "
"
+ " " + " " + " 7107300212" + " 97D2C7D26224A2DAE9A1CB501E60F395" + " EUR" + " zh_CN" + " " + " " + " 2222300212" + " 444424A2DAE9A1CB501E60F395" + " USA" + " zh_CN" + " " + " " + ""; SAXReader saxReader = new SAXReader(); Document document; try { document = saxReader.read(new ByteArrayInputStream(str1.getBytes())); Map map = Dom2Map(document); System.out.println("map>>> " + map); /* {DB_ID=EUR, CHANNEL_ID=11, USERNAME=tom, PASSWORD=sss, POOL_ID=2} {BODY={BUSLIST=[{TRACE_ID=97D2C7D26224A2DAE9A1CB501E60F395, PHONE_NO=7107300212, LANG=zh_CN, TENANT_ID=EUR}, {TRACE_ID=444424A2DAE9A1CB501E60F395, PHONE_NO=2222300212, LANG=zh_CN, TENANT_ID=USA}]}, HEADER={CHANNEL_ID=11, USERNAME=tom, PASSWORD=sss, POOL_ID=2}} */ } catch (DocumentException e) { e.printStackTrace(); } } }

2、多结点多层级的xml转map

在上面方法的基础上又开发出基于地段节点层级关系的多结点多层级xml转平级map的方法:

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.simpleproxy.dataparse.xml.ParseXMLUtils;
/**
 * 功能:通过属性文件处理XML报文
 * @author lmb 
 * @version 1.0
 * @date 2017-6-5
 */
public class ParseXmlByPropertyFile {

    /**
     * 将多结点多层级的Map转为多包体的list集合
     * @param respStr
     * @param listNode
     * @return
     */
    public static List> map2ListbyHandler(Map respStr,String listNode){
        List> resultList = new ArrayList>();
        Map map = respStr;
        String[] strArray = listNode.split(">");
        String key = null;
        Object value = null;
        for (int i = 0; i < strArray.length; i++) {
            if (map.get(strArray[i]) instanceof List) {
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    Map mapList = map;
                    if (((List>)mapList.get(strArray[i])).size() > 0) {
                        for (int j = 0; j < ((List>)mapList.get(strArray[i])).size(); j++) {
                            Map mapj = new HashMap();
                            map = ((List>)mapList.get(strArray[i])).get(j);
                            mapj.put(strArray[i+1],map.get(strArray[i + 1])+"");//listNode
                            resultList.add(mapj);
                        }
                    }
                }
                break;
            }else{
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    map = (Map) map.get(strArray[i]);
                }else{
                    Map resultMap = new HashMap();
                    resultMap.put(strArray[i],map.get(strArray[i])+"");//listNode
                    resultList.add(resultMap);
                }
            }
        }
        System.out.println("resultList >>> " + resultList);
        return resultList;      
    }

    /**
     * 根据节点的list集合将xml报文组装成多包体list
     * @param nodeList
     * @param respXml
     * @return
     */
    public static List> str2ListbyHandler(List nodeList,String respXml){
        Map resultMap = new HashMap();
        List> resultList = new ArrayList>();
        Map commonMap = new HashMap();
        int flag = 0;
        try{
            for (String node :nodeList){
                SAXReader saxReader = new SAXReader();
                Document document = saxReader.read(new ByteArrayInputStream(respXml.getBytes()));
                Element incomingForm = document.getRootElement();
                Map map =  ParseXMLUtils.Dom2Map(incomingForm);
                List> thirdList = map2ListbyHandler(map,node);
                List> listGroup = new ArrayList>();
                List> maxList = new ArrayList>();
                List> minList = new ArrayList>();
                //----------------------------------
                if (thirdList.size() > 0 && thirdList.size() < 2) {//公共参数
                    commonMap.putAll(thirdList.get(0));
                }else{//某节点下为list集合;比较list集合的大小
                    if (flag == 0) {
                        resultList = thirdList;
                    }else {
                        if (resultList.size() < thirdList.size()) {
                            maxList = thirdList;
                            minList = resultList;
                        }else{
                            maxList = resultList;
                            minList = thirdList;
                        }
                        for (int i = 0; i < maxList.size(); i++) {
                            for (int j = 0; j < minList.size(); j++) {
                                Map mapGroup = new HashMap();
                                mapGroup.putAll(thirdList.get(i));
                                mapGroup.putAll(resultList.get(j));
                                listGroup.add(mapGroup);
                                System.out.println("listGroup >> " + listGroup);
                            }
                        }
                        resultList = listGroup; 
                    }
                    flag++;
                }
                //-----------------------
            }
            if (resultList.size() == 0) {
                resultList.add(commonMap);
            }else{
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).putAll(commonMap);
                }
            }
        }catch(Exception e){
        }
        System.out.println("resultList >> " + resultList);
        return resultList;
    }

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        sb.append("");
        sb.append(" 0");
        sb.append(" 成功");
        sb.append(" ");
        sb.append("     ");
        sb.append("         105000808918");
        sb.append("         980010992");
        sb.append("         980010992)商务助手(OCS)30元");
        sb.append("         2012-11-27 16:48:12");
        sb.append("         3000-1-1 0:00:00");
        sb.append("         ");
        sb.append("             ");
        sb.append("                 101000048281");
        sb.append("                 5030");
        sb.append("                 计费区分");
        sb.append("                 CDMA预付费");
        sb.append("             ");
        sb.append("             ");
        sb.append("                 101000048282");
        sb.append("                 5031");
        sb.append("                 经分区分");
        sb.append("                 天翼商话");
        sb.append("             ");
        sb.append("         ");
        sb.append("     ");
        sb.append(" ");
        sb.append(" ");
        sb.append("     ");
        sb.append("         ");
        sb.append("             980001995");
        sb.append("             (980001995)商务助手(OCS)201209版-30元");
        sb.append("             待定...");
        sb.append("         ");
        sb.append("         ");
        sb.append("             980001996");
        sb.append("             (980001996)商务助手(OCS)201209版-50元");
        sb.append("             待定...");
        sb.append("         ");
        sb.append("         ");
        sb.append("             980001997");
        sb.append("             (980001997)商务助手(OCS)201209版-80元");
        sb.append("             待定...");
        sb.append("         ");
        sb.append("         ");
        sb.append("             980010993");
        sb.append("             (980010993)商务助手(OCS)50元");
        sb.append("             待定...");
        sb.append("         ");
        sb.append("     ");
        sb.append(" ");
        sb.append("");
        String respXml = sb.toString();
        try {
            //xml转map
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new ByteArrayInputStream(respXml.getBytes()));
            Element incomingForm = document.getRootElement();
            Map map =  ParseXMLUtils.Dom2Map(incomingForm);
            System.out.println("map >>> "+ map);
            /*
             * {resultMsg=成功, orderOffer={offer={offerSpecName=980010992)商务助手(OCS)30元, endDt=3000-1-1 0:00:00, startDt=2012-11-27 16:48:12, offerSpecId=980010992, params={param=[{offerParamId=101000048281, itemSpecName=计费区分, itemSpecId=5030, value=CDMA预付费}, {offerParamId=101000048282, itemSpecName=经分区分, itemSpecId=5031, value=天翼商话}]}, offerId=105000808918}}, resultCode=0, saleOffer={categoryNode={offer=[{summary=待定..., id=980001995, name=(980001995)商务助手(OCS)201209版-30元}, {summary=待定..., id=980001996, name=(980001996)商务助手(OCS)201209版-50元}, {summary=待定..., id=980001997, name=(980001997)商务助手(OCS)201209版-80元}, {summary=待定..., id=980010993, name=(980010993)商务助手(OCS)50元}]}}}
             */
            System.out.println("***************从map中将单个节点的值查找出来*********************");
            //map转list
            map2ListbyHandler(map,"saleOffer>categoryNode>offer>id");
            /*
             * resultList >>> [{id=980001995}, {id=980001996}, {id=980001997}, {id=980010993}]
             */
            System.out.println("***************从map中将节点集合中的所有节点值都查找出来*******************************");
            List nodeList = new ArrayList();
            nodeList.add("resultCode");
            nodeList.add("resultMsg");
            nodeList.add("orderOffer>offer>offerSpecName");
            nodeList.add("orderOffer>offer>endDt");
            nodeList.add("orderOffer>offer>startDt");
            nodeList.add("orderOffer>offer>offerSpecId");
            nodeList.add("orderOffer>offer>offerId");
            nodeList.add("orderOffer>offer>params>param>offerParamId");
            nodeList.add("orderOffer>offer>params>param>itemSpecName");
            nodeList.add("orderOffer>offer>params>param>itemSpecId");
            nodeList.add("orderOffer>offer>params>param>value");
            nodeList.add("saleOffer>categoryNode>offer>id");
            nodeList.add("saleOffer>categoryNode>offer>summary");
            nodeList.add("saleOffer>categoryNode>offer>name");
            str2ListbyHandler(nodeList,respXml);
            /**
             * [{offerParamId=101000048281, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001995, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048282, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001995, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048281, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001996, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048282, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001996, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048281, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001997, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048282, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980001997, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12,
             *       name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048281, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980010993, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}, 
             * {offerParamId=101000048282, summary=待定..., endDt=3000-1-1 0:00:00, itemSpecId=5031, id=980010993, resultMsg=成功, 
             *      itemSpecName=经分区分, offerSpecName=980010992)商务助手(OCS)30元, offerSpecId=980010992, startDt=2012-11-27 16:48:12, 
             *      name=(980010993)商务助手(OCS)50元, resultCode=0, value=天翼商话, offerId=105000808918}]
             */
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }   
}

你可能感兴趣的:(Java)