当前位置:网站首页>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)));
// }
}
边栏推荐
- Drag to change order
- Scenario practice: quickly build wordpress blog system based on function calculation
- Hutool post requests to set the body parameter to JSON data
- The GPG keys listed for the "MySQL 8.0 community server" repository are already ins
- 刨析《C语言》【进阶】付费知识【一】
- Date processing tool class dateutils (tool class 1)
- Today's question -2022/7/4 modify string reference type variables in lambda body
- Livox激光雷达硬件时间同步---PPS方法
- AcWing 344. Solution to the problem of sightseeing tour (Floyd finding the minimum ring of undirected graph)
- ROS learning (23) action communication mechanism
猜你喜欢

CISP-PTE实操练习讲解(二)
![[unique] what is the [chain storage structure]?](/img/cd/be18c65b9d7faccc3c9b18e3b2ce8e.png)
[unique] what is the [chain storage structure]?

鼠标右键 自定义

CISP-PTE之命令注入篇

ROS learning (21) robot slam function package -- installation and testing of orbslam

猫猫回收站

Make DIY welding smoke extractor with lighting

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

New job insights ~ leave the old and welcome the new~

454 Baidu Mianjing 1
随机推荐
centos8安装mysql报错:The GPG keys listed for the “MySQL 8.0 Community Server“ repository are already ins
AcWing 1142. Busy urban problem solving (minimum spanning tree)
ROS學習(23)action通信機制
dvajs的基础介绍及使用
Cisp-pte practice explanation (II)
Gin introduction practice
一文带你走进【内存泄漏】
爬虫实战(六):爬笔趣阁小说
centos8 用yum 安装MySQL 8.0.x
初识MySQL
Use nodejs to determine which projects are packaged + released
字符串转成日期对象
CISP-PTE实操练习讲解(二)
糊涂工具类(hutool)post请求设置body参数为json数据
The use of video in the wiper component causes full screen dislocation
js如何快速创建一个长度为 n 的数组
AcWing 904. 虫洞 题解(spfa求负环)
String to date object
Set up [redis in centos7.x]
AcWing 1148. 秘密的牛奶运输 题解(最小生成树)