当前位置:网站首页>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)));
// }
}
边栏推荐
- 使用nodejs完成判断哪些项目打包+发版
- Mysqlbackup restores specific tables
- ROS学习(21)机器人SLAM功能包——orbslam的安装与测试
- Golang foundation - data type
- Errors made in the development of merging the quantity of data in the set according to attributes
- CISP-PTE实操练习讲解(二)
- JS ES5也可以創建常量?
- Livox激光雷达硬件时间同步---PPS方法
- Compile command line terminal swift
- Blue Bridge Cup 2022 13th provincial competition real topic - block painting
猜你喜欢
C语言关于链表的代码看不懂?一篇文章让你拿捏二级指针并深入理解函数参数列表中传参的多种形式
Appium automation test foundation uiautomatorviewer positioning tool
How did partydao turn a tweet into a $200million product Dao in one year
Blue Bridge Cup 2022 13th provincial competition real topic - block painting
[unique] what is the [chain storage structure]?
JVM 内存模型
ROS learning (XX) robot slam function package -- installation and testing of rgbdslam
sql中批量删除数据---实体中的集合
Livox激光雷达硬件时间同步---PPS方法
刨析《C语言》【进阶】付费知识【一】
随机推荐
Gin introduction practice
Threadlocalutils (tool class IV)
Treadpoolconfig thread pool configuration in real projects
AcWing 344. 观光之旅题解(floyd求无向图的最小环问题)
刨析《C语言》【进阶】付费知识【二】
蓝桥杯2022年第十三届省赛真题-积木画
Today's question -2022/7/4 modify string reference type variables in lambda body
Box stretch and pull (left-right mode)
Centros 8 installation MySQL Error: The gpg Keys listed for the "MySQL 8.0 Community Server" repository are already ins
一片叶子两三万?植物消费爆火背后的“阳谋”
AcWing 1140. 最短网络 (最小生成树)
CISP-PTE实操练习讲解(二)
AcWing 1142. Busy urban problem solving (minimum spanning tree)
公钥\私人 ssh避password登陆
Analyze "C language" [advanced] paid knowledge [II]
Use nodejs to determine which projects are packaged + released
NPM install compilation times "cannot read properties of null (reading 'pickalgorithm')“
JS ES5也可以創建常量?
BigDecimal 的正确使用方式
The use of video in the wiper component causes full screen dislocation