1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Dom4j解析xml字符串

Dom4j解析xml字符串

时间:2022-01-20 09:42:58

相关推荐

Dom4j解析xml字符串

Dom4j解析xml字符串到List或JSON

通用代码

依赖jar

import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import com.alibaba.fastjson.JSON;

/*** 选择需要返回的格式: 1、返回 List<Map>\2、返回 Map* @param xml* @return*/@SuppressWarnings("all")public static List<Map<String, Object>> parseXML(String xml) {// 1、 List<Map>List<Map<String, Object>> resultList = new ArrayList<>(); // 2、 MapMap<String, Object> resultMap = new HashMap<>(); Document document = null;try {document = DocumentHelper.parseText(xml);Element root = document.getRootElement();Iterator<Element> rootIter = root.elementIterator();while (rootIter.hasNext()) {Element ele = rootIter.next();Map<String, Object> parenMap = new HashMap<>();chile(ele, null, parenMap, null, null);// 1、listresultList.add(parenMap);// 2、mapresultMap.put(ele.getName(), parenMap);}} catch (Exception e) {e.printStackTrace();}// toJSONString listJSON = JSON.toJSONString(resultList);String mapJSON = JSON.toJSONString(resultMap);System.out.println(listJSON);System.out.println(JSON.toJSONString(mapJSON));return resultList;}

@SuppressWarnings("all")public static void chile(Element ele, String keyName, Map<String, Object> parenMap, Map<String, Object> childMap,List<Map<String, Object>> childData) {Iterator<Element> childIter = ele.elementIterator();while (childIter.hasNext()) {Element attr = childIter.next();Iterator<Element> childIter2 = attr.elementIterator();if (childIter2.hasNext()) {Element attr2 = childIter2.next();Map<String, Object> childMap2 = new HashMap<>();List<Map<String, Object>> childData2 = new ArrayList<>();chile(attr, attr.getName(), parenMap, childMap2, childData2);} else if (keyName != null) {childMap.put(attr.getName().trim(), attr.getText().trim());} else {parenMap.put(attr.getName().trim(), attr.getText().trim());}}if (keyName != null && childMap != null && !childMap.isEmpty()) {if (parenMap != null && parenMap.get(keyName) != null) {List<Map<String, Object>> object = (List<Map<String, Object>>) parenMap.get(keyName);object.add(childMap);} else {childData.add(childMap);parenMap.put(keyName, childData);}}}

public static void main(String[] args) {String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Xml>"+ "<Head><Version>V1.0</Version><SecurityMode>MD5</SecurityMode><CheckSum>123</CheckSum><From>Booking</From><To>1.1.1.1</To></Head>"+ "<Response><Status>1</Status><Code>0</Code><Message></Message>"+ "<Data><T>"+ "<R><ClassId>182030</ClassId><ClassDate>-03-23</ClassDate><DayType>下午</DayType>"+ "<Postion>特需诊室</Postion><ServiceType>特需全自费408</ServiceType></R>"+ "<R><ClassId>183198</ClassId><ClassDate>-03-30</ClassDate><DayType>下午</DayType>"+ "<Postion>特需诊室</Postion><ServiceType>特需全自费408</ServiceType></R>"+ "</T></Data></Response></Xml>";parseXML(xml);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。