Xml字符串转Map

说明:除head、body节点合并为一个Map,其余的都进行List转换;
比如XML:
Xml字符串转Map
文章图片
Xml字符串转Map
文章图片


Xml字符串转Map
文章图片


则节点为一个Map,VALUE为List,其中节点不显示名称,具体代码如下:

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.DocumentHelper; import org.dom4j.Element; public class XmlUtils { private static final String HEAD = "head"; private static final String BODY = "body"; public static void main(String[] args) throws DocumentException { String xml = "3300038000500436222221234567890012016051015123810TEST01234310066865018010123060S10.01201605测试0.013100012379000000001测试账号021.0111111111100000001测试账号021.01111111111"; System.out.println(parseXmlStr(xml).toString()); }/** * 解析XML字符串 * * @param xml * @return * @throws DocumentException */ private static Map parseXmlStr(String xml) throws DocumentException { Document document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); return parseElement(root); }/** * 解析Element * * @param root * @return */ @SuppressWarnings("unchecked") private static Map parseElement(Element root) { String rootName = root.getName(); Iterator rootItor = root.elementIterator(); Map rMap = new HashMap<>(); List rList = new ArrayList<>(); Map rsltMap = null; while (rootItor.hasNext()) { Element tmpElement = rootItor.next(); String name = tmpElement.getName(); if (rsltMap == null || (!HEAD.equals(name) && !BODY.equals(name) && !tmpElement.isTextOnly())) { if (!HEAD.equals(name) && !BODY.equals(name) && !tmpElement.isTextOnly() && rsltMap != null) { rList.add(rsltMap); } rsltMap = new HashMap<>(); } if (!tmpElement.isTextOnly()) { Iterator headItor = tmpElement.elementIterator(); while (headItor.hasNext()) { Element hElement = headItor.next(); if (hElement.isTextOnly()) { rsltMap.put(hElement.getName(), hElement.getTextTrim()); } else { rsltMap.putAll(parseElement(hElement)); } } } } rList.add(rsltMap); rMap.put(rootName, rList); return rMap; }}



测试结果:
{ap=[{summary=测试0.01, tr_time=151238, cert_no=TEST01234, channel=0, tr_code=330003, sum=1, type=S, pay_month=201605, req_no=123456789001, user_no=22222, tr_acdt=20160510, sum_amt=0.01, reserved=, atom_tr_count=1, pay_acno=310066865018010123060, busi_no=3100012379, corp_no=8000500436, selsec_flg=0, tran=[{acname=测试账号, card_no=00000001, card_flag=0, amt=21.01, busino=111111111}, {acname=测试账号, card_no=00000001, card_flag=0, amt=21.01, busino=111111111}]}]}

【Xml字符串转Map】

    推荐阅读