当前位置:网站首页>XML to map tool class xmlmaputils (tool class V)
XML to map tool class xmlmaputils (tool class V)
2022-07-07 01:57:00 【Novice Zhang~】
package com.menglar.soap.item.common.utils;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/** * Provide Map<String,Object> turn XML,XML turn Map<String,Object> */
public class XmlMap {
/** * * adopt Map establish XML,Map Multi level conversion is possible * * @param params * @return String-->XML */
public static String createXmlByMap(String parentName,Map<String, Object> params,boolean isCDATA){
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = iteratorXml(doc.getRootElement(),parentName,params,isCDATA);
return formatXML(xml);
}
/** * * adopt Map establish XML,Map Multi level conversion is possible * You can customize parent node * * @param params * @return String-->XML */
public static String createXmlByMap(String parentName,Map<String, Object> params){
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = iteratorXml(doc.getRootElement(),parentName,params,false);
return formatXML(xml);
}
/** * * adopt Map establish XML,Map It can rotate in multiple layers * Fixed nodes parent by Document * * @param params * @return String-->XML */
public static String createXmlByMap(Map<String, Object> params){
String parentName = "Request";
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = iteratorXml(doc.getRootElement(),parentName,params,false);
return formatXML(xml);
}
/** * * MapToXml Loop through the creation xml node * In this method value Add CDATA identifier * * @param element The root node * @param parentName Child node name * @param params map data * @return String-->Xml */
@SuppressWarnings("unchecked")
public static String iteratorXml(Element element,String parentName,Map<String,Object> params,boolean isCDATA) {
Element e = element.addElement(parentName);
Set<String> set = params.keySet();
for (Iterator<String> it = set.iterator(); it.hasNext();) {
String key = (String) it.next();
if(params.get(key) instanceof Map) {
iteratorXml(e,key,(Map<String,Object>)params.get(key),isCDATA);
}else {
String value = params.get(key)==null?"":params.get(key).toString();
if(!isCDATA) {
e.addElement(key).addText(value);
}else {
e.addElement(key).addCDATA(value);
}
}
}
return e.asXML();
}
/** * format xml, Display as easy to see XML Format * * @param inputXML * @return */
public static String formatXML(String inputXML){
String requestXML = null;
XMLWriter writer = null;
Document document = null;
try {
SAXReader reader = new SAXReader();
document = reader.read(new StringReader(inputXML));
if (document != null) {
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat(" ", true);// format , The space before each level
format.setNewLineAfterDeclaration(false); //xml Whether to add blank lines to the declaration and content
format.setSuppressDeclaration(false); // Whether to set up xml Declaration header
format.setNewlines(true); // Set up branches
writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
requestXML = stringWriter.getBuffer().toString();
}
return requestXML;
} catch (Exception e1) {
e1.printStackTrace();
return null;
}finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
/** * * adopt XML Convert to Map<String,Object> * * @param xml by String Type of Xml * @return The first is Root node ,Root After node is Root The elements of , If it is multi-layer , Can pass key Get next level Map */
public static Map<String, Object> createMapByXml(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
e.printStackTrace();
}
Map<String, Object> map = new HashMap<String, Object>();
if (doc == null)
return map;
Element rootElement = doc.getRootElement();
elementTomap(rootElement,map);
return map;
}
/*** * * XmlToMap The core approach , There are recursive calls * * @param map * @param ele */
@SuppressWarnings("unchecked")
public static Map<String, Object> elementTomap (Element outele,Map<String,Object> outmap) {
List<Element> list = outele.elements();
int size = list.size();
if(size == 0){
outmap.put(outele.getName(), outele.getTextTrim());
}else{
Map<String, Object> innermap = new HashMap<String, Object>();
for(Element ele1 : list){
String eleName = ele1.getName();
Object obj = innermap.get(eleName);
if(obj == null){
elementTomap(ele1,innermap);
}else{
if(obj instanceof java.util.Map){
List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
list1.add((Map<String, Object>) innermap.remove(eleName));
elementTomap(ele1,innermap);
list1.add((Map<String, Object>) innermap.remove(eleName));
innermap.put(eleName, list1);
}else{
elementTomap(ele1,innermap);
((List<Map<String, Object>>)obj).add(innermap);
}
}
}
outmap.put(outele.getName(), innermap);
}
return outmap;
}
/** * Map or JSON convert to Xml * * fastJSON Realized Map<String,Object> So it is directly transmitted here json Can also be the */
public static String mapToXML(Map map, StringBuffer sb) {
Set set = map.keySet();
for (Iterator it = set.iterator(); it.hasNext(); ) {
String key = (String) it.next();
Object value = map.get(key);
if (null == value)
value = "";
if (value.getClass().getName().equals("java.util.ArrayList")) {
LinkedList list = (LinkedList) map.get(key);
sb.append("<" + key + ">");
for (int i = 0; i < list.size(); i++) {
HashMap hm = (HashMap) list.get(i);
mapToXML(hm, sb);
}
sb.append("</" + key + ">");
} else {
if (value instanceof HashMap) {
sb.append("<" + key + ">");
mapToXML((HashMap) value, sb);
sb.append("</" + key + ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}
}
}
return sb.toString();
}
//public static void main(String[] args) {
// Map<String,Object> result = new HashMap<String,Object>();
// result.put("Request", "getData");
// Map<String,Object> map = new HashMap<String,Object>();
// map.put("data", "2018-01-01");
// map.put("name", "jack");
// result.put("Data", map);
// System.out.println(createXmlByMap(result));
// System.out.println(createXmlByMap("Parent", result));
// System.out.println(createXmlByMap("Parent", result,true));
// System.out.println(createMapByXml(createXmlByMap(result)));
// }
}
边栏推荐
- Long press the button to execute the function
- 盒子拉伸拉扯(左右模式)
- Shortcut keys commonly used in idea
- ROS學習(23)action通信機制
- AcWing 1142. 繁忙的都市 题解(最小生成树)
- 使用nodejs完成判断哪些项目打包+发版
- AcWing 1141. LAN problem solving (kruskalkruskal finding the minimum spanning tree)
- Redis tool class redisutil (tool class III)
- ZOJ Problem Set – 2563 Long Dominoes 【如压力dp】
- 一片叶子两三万?植物消费爆火背后的“阳谋”
猜你喜欢

How can I code for 8 hours without getting tired.

Baidu flying general BMN timing action positioning framework | data preparation and training guide (Part 1)

sql中批量删除数据---实体中的集合

ROS学习(21)机器人SLAM功能包——orbslam的安装与测试

AcWing 345. Cattle station solution (nature and multiplication of Floyd)

猫猫回收站

Make DIY welding smoke extractor with lighting

Comparison of picture beds of free white whoring

一文带你走进【内存泄漏】

开发中对集合里面的数据根据属性进行合并数量时犯的错误
随机推荐
ROS learning (23) action communication mechanism
Set WordPress pseudo static connection (no pagoda)
ROS學習(23)action通信機制
Long press the button to execute the function
AcWing 1148. Secret milk transportation problem solution (minimum spanning tree)
How did partydao turn a tweet into a $200million product Dao in one year
JS ES5也可以創建常量?
百度飞将BMN时序动作定位框架 | 数据准备与训练指南 (上)
736. LISP syntax parsing: DFS simulation questions
Date processing tool class dateutils (tool class 1)
2022/0524/bookstrap
According to the analysis of the Internet industry in 2022, how to choose a suitable position?
字符串的相关编程题
AcWing 1148. 秘密的牛奶运输 题解(最小生成树)
AcWing 1140. Shortest network (minimum spanning tree)
LeetCode. Sword finger offer 62 The last remaining number in the circle
mongodb查看表是否导入成功
AcWing 1141. LAN problem solving (kruskalkruskal finding the minimum spanning tree)
Modify the system time of Px4 flight control
AcWing 345. Cattle station solution (nature and multiplication of Floyd)