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)


相关推荐

  • 【EF】DbFirst实现增删改查

    【EF】DbFirst实现增删改查【EF】DbFirst实现增删改查

  • Awvs详细使用教程「建议收藏」

    Awvs详细使用教程「建议收藏」Awvs的是一款非常好用的web漏洞扫描工具,他的扫描速度比较快,可以自己选择扫描速度,比较灵活。Awvs分为老的版本和新版本,下面我介绍的是新版本的功能和用法。功能介绍如下:仪表盘(监视器)功能,添加目标功能,漏洞排序功能,扫描功能,发现功能,用户功能,扫描配置功能,网络扫描功能,追踪器功能,防火墙设置,邮件设置,引擎,时间排除功能,代理功能,常规设置主要使用的功能是前面的6个,后面的根据个人的需要进行配置详细介绍如下:Dashboard功能:翻译意思仪表盘(监视器),可以对扫描对扫描

    2022年10月22日
  • Spring整合MyBatis——超详细

    Spring整合MyBatis——超详细Spring整合MyBatis——超详细一、Spring整合MyBatis的三个关键点二、整合步骤1、创建一个Maven项目2、在pom.xml文件中添加jar包的依赖2、配置MyBatis文件(1)新建一个实体类的包和User实体类(2)编写实体类(3)新建Mapper接口包和UserMapper接口(3)新建jdbc资源文件jdbc-config.properties(4)新建mybatis配置文件mybatis.xml(5)新建logj4j的日志配置文件log4j.properties

  • 分类信息网站大全

    分类信息网站大全

  • python读取文件如何去除空格_python读取txt文件时怎么去掉空格

    python读取文件如何去除空格_python读取txt文件时怎么去掉空格python属于什么型语言python通过什么实现映射Python读取TXT文件可以通过replace()函数来去除TXT文件中的空格,基本结构:replace(to_replace,value)前面是需要替换的值,后面是替换后的值。代码如下:importosimportsys#os.chdir(‘E:\\’)#跳到D盘#ifnotos.path.exists(‘1.txt’):…

  • c# 第14节 字符方法、转义字符、字符串的方法[通俗易懂]

    c# 第14节 字符方法、转义字符、字符串的方法

发表回复

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

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