前言【
最近在写一个业务,由于调UPS物流的接口返回的是一个xml格式的数据结果,我现在要拿到xml中某个节点的值,而这个xml数据是多节点多层级的,并且这某个节点的值有可能只有一条值,有可能有多条,如下:
大概是这样的结构:为了简要,我做简单显示,真正的结构层级跟这差不多
<class> <student> <name>aaaaaa</name> <girlfriend>bbb</girlfriend> <girlfriend>ccc</girlfriend> </student> </class>
>>>>由于girlfriend的值是不确定的,有可能一个,或多个>>>>
<class> <student> <name>aaaaaa</name> <girlfriend>bbb</girlfriend> </student> </class>
//现在要把当前xml转成map,并且还要遍历map,拿到girlfriend的值,于girlfriend的值有可能是多个
//所以当xml中的节点girlfriend的值不同时,我们都要解析成多层级的map,并拿到girlfriend的值
】
网上百度了很久,终于找到一位大神写的一个xml转map的工具,并且还附带从map中查找某层级的子节点数据,借鉴博客:https://blog.csdn.net/lmb55/article/details/77507385
我在他的方法上做了一些小改动,因为我要根据classs>student>girlfriend拿到一个这样{girlfriend=[bbb, ccc]},或{girlfriend=[bbb]},所以不管一个值还是多个值我都要放到map中的list中,但他的map取list数据方法只能取一到一个list值如[bbb, ccc]
好了,来解析一下:
第一步:把xml转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; }
//调用上面的xml转map方法:
//xml转map
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new ByteArrayInputStream(respXml.getBytes()));
Element incomingForm = document.getRootElement();
Map map = 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元}]}}}
*/
第二步:xml已经转成map数据结构了,下面要根据节点的层级路径,拿到你想要的节点值
/** * 将多结点多层级的Map转为多包体的list集合 * @param respStr * @param listNode * @return */ @SuppressWarnings("unchecked") public static Map<String, List<String>> map2ListbyHandler(Map respStr,String listNode){ List<String> resultList = new ArrayList<String>(); Map<String, List<String>> resultMap = new HashMap<>(); 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 && 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) { // Map mapj = new HashMap(); // List<Map<String,Object>> list = ((List<Map<String,Object>>)mapList.get(strArray[i])); resultList = ((List<String>)mapList.get(strArray[i])); if(resultList.size() > 0){ resultMap.put(strArray[i], resultList); } return resultMap; } } break; }else{ if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) { map = (Map) map.get(strArray[i]); }else{ //说明没有此节点只有一个值,直接从map里把值取出放resultList中 resultList.add(map.get(strArray[i]).toString()); resultMap.put(strArray[i], resultList);//listNode } } } return resultMap; }
//调用上面的遍历map取数据方法:原博客返回的是一个list,我给改成了map,因为我想要{girlfriend=[bbb, ccc]},或{girlfriend={bbb}}这种结果数据,方便我根据节点名称取值
System.out.println("***************从map中将单个节点的值查找出来*********************");
//map转list
Map resultMap = XmlToMapUtil01.map2ListbyHandler(map,"student>age");
System.out.println(resultMap.toString());
》》》》》》》》》》》》》》》》》》》》》》》》》》》》
好了,下面放上全部代码,一个XmlToMapUtil01.java工具类代码,和一个TestXmlToMap01.java用来测试工具类的文件
XmlToMapUtil01.java工具类
package com.saoptest.test03; 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; public class XmlToMapUtil01 { /** * 将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; } //=========================上面是单节点多层级的xml转map==================================== //=========================下面是多节点多层级的xml转map==================================== /** * 将多结点多层级的Map转为多包体的list集合 * @param respStr * @param listNode * @return */ @SuppressWarnings("unchecked") public static Map<String, List<String>> map2ListbyHandler(Map respStr,String listNode){ List<String> resultList = new ArrayList<String>(); Map<String, List<String>> resultMap = new HashMap<>(); 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 && 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) { // Map mapj = new HashMap(); // List<Map<String,Object>> list = ((List<Map<String,Object>>)mapList.get(strArray[i])); resultList = ((List<String>)mapList.get(strArray[i])); if(resultList.size() > 0){ resultMap.put(strArray[i], resultList); } return resultMap; } } break; }else{ if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) { map = (Map) map.get(strArray[i]); }else{ //说明没有此节点只有一个值,直接从map里把值取出放resultList中 resultList.add(map.get(strArray[i]).toString()); resultMap.put(strArray[i], resultList);//listNode } } } return resultMap; } //===============map测试========================== 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 = 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(); } } }
TestXmlToMap01.java
package com.saoptest.test03; import java.io.ByteArrayInputStream; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class TestXmlToMap01 { public static void main(String[] args) throws Exception { //xml转json String xml = "<class><student><name>aaaaaa</name><girlfriend>bbb</girlfriend><girlfriend>ccc</girlfriend></student></class>"; // String xml = "<class><student><name>aaaaaa</name><girlfriend>bbb</girlfriend></student></class>"; // String xml = "<class><student><name>aaaaaa</name><age>21</age></student><student><name>bbbbbb</name><age>22</age></student></class>"; // String xml = "<class><student><name>aaaaaa</name><age>21</age></student></class>"; //xml转map SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes())); Element incomingForm = document.getRootElement(); Map map = XmlToMapUtil01.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 Map<String, List<String>> resultMap = XmlToMapUtil01.map2ListbyHandler(map,"student>girlfriend"); List<String> list = resultMap.get("girlfriend"); System.out.println("resultMap=" + resultMap.toString()); if(!"null".equals(resultMap.get("girlfriend").toString())){ System.out.println("有数据:" + resultMap.get("girlfriend")); }else{ System.out.println("没数据:" + resultMap.get("girlfriend")); } // Map<String, List<String>> map1 = new HashMap<String, List<String>>(); // List<String> lists = new ArrayList<String>(); // lists.add("bbb"); // lists.add("ccc"); // map1.put("girlfriend", lists); // System.out.println("map1====" + map1.toString()); // System.out.println(map1.get("girlfriend")); // System.out.println(map1.get("girlfriend").get(0) + "=====" + map1.get("girlfriend").get(1)); // } }