java解析xml转为Map

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

大家好,又见面了,我是你们的朋友全栈君。

之前开发过一个解析多层级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<String, Object> Dom2Map(Document doc){  
        Map<String, Object> map = new HashMap<String, Object>();  
        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 = "<HEADER>" +
                " <POOL_ID>2</POOL_ID>" +
                " <DB_ID>EUR</DB_ID>" +
                " <CHANNEL_ID>11</CHANNEL_ID>" +
                " <USERNAME>tom</USERNAME>" +
                " <PASSWORD>sss</PASSWORD>" +
                " </HEADER>";
        String str2 = "<ROOT>" +
                     " <HEADER>" +
                     " <POOL_ID>2</POOL_ID>" +
                     " <CHANNEL_ID>11</CHANNEL_ID>" +
                     " <USERNAME>tom</USERNAME>" +
                     " <PASSWORD>sss</PASSWORD>" +
                     " </HEADER>" +
                     " <BODY>" +
                     " <BUSLIST>" +
                     " <PHONE_NO>7107300212</PHONE_NO>" +
                     " <TRACE_ID>97D2C7D26224A2DAE9A1CB501E60F395</TRACE_ID>" +
                     " <TENANT_ID>EUR</TENANT_ID>" +
                     " <LANG>zh_CN</LANG>" +
                     " </BUSLIST>" +
                     " <BUSLIST>" +
                     " <PHONE_NO>2222300212</PHONE_NO>" +
                     " <TRACE_ID>444424A2DAE9A1CB501E60F395</TRACE_ID>" +
                     " <TENANT_ID>USA</TENANT_ID>" +
                     " <LANG>zh_CN</LANG>" +
                     " </BUSLIST>" +
                     " </BODY>" +
                     "</ROOT>";
        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<Map<String,Object>> map2ListbyHandler(Map respStr,String listNode){
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        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<String,Object> mapList = map;
                    if (((List<Map<String,Object>>)mapList.get(strArray[i])).size() > 0) {
                        for (int j = 0; j < ((List<Map<String,Object>>)mapList.get(strArray[i])).size(); j++) { 
   
                            Map mapj = new HashMap();
                            map = ((List<Map<String,Object>>)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<String,Object> resultMap = new HashMap<String,Object>();
                    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<Map<String,Object>> str2ListbyHandler(List<String> nodeList,String respXml){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        Map<String,Object> commonMap = new HashMap<String,Object>();
        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<Map<String,Object>> thirdList = map2ListbyHandler(map,node);
                List<Map<String,Object>> listGroup = new ArrayList<Map<String,Object>>();
                List<Map<String,Object>> maxList = new ArrayList<Map<String,Object>>();
                List<Map<String,Object>> minList = new ArrayList<Map<String,Object>>();
                //----------------------------------
                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<String,Object> mapGroup = new HashMap<String,Object>();
                                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("<response>");
        sb.append(" <resultCode>0</resultCode>");
        sb.append(" <resultMsg>成功</resultMsg>");
        sb.append(" <orderOffer>");
        sb.append(" <offer>");
        sb.append(" <offerId>105000808918</offerId>");
        sb.append(" <offerSpecId>980010992</offerSpecId>");
        sb.append(" <offerSpecName>980010992)商务助手(OCS)30元</offerSpecName>");
        sb.append(" <startDt>2012-11-27 16:48:12</startDt>");
        sb.append(" <endDt>3000-1-1 0:00:00</endDt>");
        sb.append(" <params>");
        sb.append(" <param>");
        sb.append(" <offerParamId>101000048281</offerParamId>");
        sb.append(" <itemSpecId>5030</itemSpecId>");
        sb.append(" <itemSpecName>计费区分</itemSpecName>");
        sb.append(" <value>CDMA预付费</value>");
        sb.append(" </param>");
        sb.append(" <param>");
        sb.append(" <offerParamId>101000048282</offerParamId>");
        sb.append(" <itemSpecId>5031</itemSpecId>");
        sb.append(" <itemSpecName>经分区分</itemSpecName>");
        sb.append(" <value>天翼商话</value>");
        sb.append(" </param>");
        sb.append(" </params>");
        sb.append(" </offer>");
        sb.append(" </orderOffer>");
        sb.append(" <saleOffer>");
        sb.append(" <categoryNode id = \"100472\">");
        sb.append(" <offer>");
        sb.append(" <id>980001995</id>");
        sb.append(" <name>(980001995)商务助手(OCS)201209版-30元</name>");
        sb.append(" <summary>待定...</summary>");
        sb.append(" </offer>");
        sb.append(" <offer>");
        sb.append(" <id>980001996</id>");
        sb.append(" <name>(980001996)商务助手(OCS)201209版-50元</name>");
        sb.append(" <summary>待定...</summary>");
        sb.append(" </offer>");
        sb.append(" <offer>");
        sb.append(" <id>980001997</id>");
        sb.append(" <name>(980001997)商务助手(OCS)201209版-80元</name>");
        sb.append(" <summary>待定...</summary>");
        sb.append(" </offer>");
        sb.append(" <offer>");
        sb.append(" <id>980010993</id>");
        sb.append(" <name>(980010993)商务助手(OCS)50元</name>");
        sb.append(" <summary>待定...</summary>");
        sb.append(" </offer>");
        sb.append(" </categoryNode>");
        sb.append(" </saleOffer>");
        sb.append("</response>");
        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<String> nodeList = new ArrayList<String>();
            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();
        }
    }   
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/138724.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • VMWare14 安装Mac OS系统(操作图解)

    VMWare14 安装Mac OS系统(操作图解)近日恰逢双十一,瞅了瞅自己干瘪的钱包,没忍心入手期待已久的macPro,只好在虚拟机里玩一下mac好了,等以后钱包傲气的时候再来个真实的。安装环境:windows10VMWare14.2VMwareWorkstationPro14已安装或自行安装Unlocker(链接:https://pan.baid…

  • 如何用正确的姿势发微信群通知?「建议收藏」

    如何用正确的姿势发微信群通知?「建议收藏」人数众多的微信群里,你如何管理通知发放进度?想不想使用更高效的办法发通知?本文推荐给你一款小程序,帮助你轻松搞定微信群通知。(由于微信公众号外部链接的限制,文中的部分链接可能无法正确打开。如有需要,请点击文末的“阅读原文”按钮,访问可以正常显示外链的版本。)两难微信群被用来发通知,其实是工具使用场景错位。因为微信并不是高效办公的工具。否则腾讯也就不必开发企业微信,和

  • minipcie串口卡_minipcie接口定义图解

    minipcie串口卡_minipcie接口定义图解简介LCminiPCIe系列miniPCIe接口CAN卡,具有1~2路CAN通道和一路PCIExpressmini接口,插到工控机或单板电脑的PCIExpressmini卡槽上,快速扩展出1~2路CAN通道。CAN接口电气隔离高达2500VDC,具有优秀的EMC性能,可靠性测试项目:ESD接触放电8KV、浪涌±1KV、脉冲群±2KV,工业级,通过CE-EMC和FCC认证。配套测试软件L…

  • fiddler 抓包详细教程「建议收藏」

    为什么要先学fiddler?学习接口测试必学http协议,如果直接先讲协议,我估计小伙伴们更懵,为了更好的理解协议,先从抓包开始。结合抓包工具讲http协议更容易学一些。抓firefox上https请求fiddler是一个很好的抓包工具,默认是抓http请求的,对于pc上的https请求,会提示网页不安全,这时候需要在浏览器上安装证书。一、网页不安全1.用fiddler抓包时候,打开百…

  • 全球单片机的主要厂商和主要型号介绍图_51单片机包括哪些型号

    全球单片机的主要厂商和主要型号介绍图_51单片机包括哪些型号
    全球单片机的主要厂商和主要型号介绍
    PIC单片机: 
      是MICROCHIP公司的产品,其突出的特点是体积小,功耗低,精简指令集,抗干扰性好,可靠性高,有较强的模拟接口,代码保密性好,大部分芯片有其兼容的FLASH程序存储器的芯片. 
    EMC单片机:
      是台湾义隆公司的产品,有很大一部分与PIC 8位单片机兼容,且相兼容产品的资源相对比PIC的多,价格便宜,有很多系列可选,但抗干扰较差. 
    ATMEL单片机(51单片机):
    ATME

    2022年10月19日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号