XMl转Map-map调用公共模板
效果
<?xmlversion="1.0"encoding="utf-8"?>
<SERVICE>
<SERVICE_HEADER>
<apple>苹果大苹果小苹果好吃的不得了</apple>
</SERVICE_HEADER>
<SERVICE_BODY>
<INFORMATION>
<USER>
<NAME>姚明多大</NAME>
<AGE>?</AGE>
</USER>
<USER>
<NAME>姚明多高</NAME>
<AGE>反正比你高</AGE>
</USER>
</INFORMATION>
</SERVICE_BODY>
</SERVICE>
测试代码
package com.sunline.nfs.process; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; public class velocityxml {
static Map<String,Object> jsonMap = new LinkedHashMap<String,Object>(); public static Map recursinMap(Map<String,Object> map){
net.sf.json.JSONObject jObject = new net.sf.json.JSONObject();
for(String key:map.keySet()){
String str = map.get(key).toString();
if(str.startsWith("{")){
/*com.alibaba.fastjson.JSONObject jObject = JSON.parseObject(str);*/
Map<String,Object> map2 = jObject.fromObject(str);
if(!map.toString().endsWith(map2.toString()+"}")){
int i = map.toString().indexOf(map2.toString())+;
String value ="{" + map.toString().substring((i+map2.toString().length()),map.toString().length());
map2.put(key, value);
}
return recursinMap(map2);
}
else{
if(str.startsWith("[")){
JSONArray tmpMaps = JSONArray.fromObject(str);
jsonMap.put(key, tmpMaps);
}
else{
jsonMap.put(key, str);
}
}
}
return jsonMap;
}
@SuppressWarnings("null")
public static void main(String[] args) throws IOException{
String filename = "partten.txt";
String json = readJson(filename);
json = xmlToJson(json);
net.sf.json.JSONObject jObject = new net.sf.json.JSONObject();
Map<String,Object> tmpmap = jObject.fromObject(json);
Map<String,Object> map = recursinMap(tmpmap);
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "class");
//设置velocity资源加载方式为file时的处理类
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//实例化一个VelocityEngine对象
VelocityEngine velocityEngine=new VelocityEngine(properties); //实例化一个VelocityContext
VelocityContext context=new VelocityContext();
for(Object key :jsonMap.keySet()){
context.put((String)key, jsonMap.get(key));
}
//实例化一个StringWriter
StringWriter writer=new StringWriter();
velocityEngine.mergeTemplate("patternxml.txt", "gbk", context, writer);
String str = writer.toString();
str = str.replaceAll("\\s*", "");
System.out.println(str); }
public static String readJson(String filename){
Resource resource =new ClassPathResource(filename);
File file;
try {
file = resource.getFile();
BufferedReader reader= new BufferedReader(new FileReader(file));
String temp=null;
String str="";
while((temp=reader.readLine())!=null){
str = str + temp;
}
return str;
} catch (IOException e) {
e.printStackTrace();
} return null;
} public static void dom4j2Json(Element element, JSONObject json) {
// 如果是属性
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !isEmpty(element.getText())) {// 如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
} for (Element e : chdEl) {// 有子元素
if (!e.elements().isEmpty()) {// 子元素也有子元素
JSONObject chdjson = new JSONObject();
dom4j2Json(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {// 如果此元素已存在,则转为jsonArray
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
} else {// 子元素没有子元素
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
}
} public static boolean isEmpty(String str) {
if (str == null || str.trim().isEmpty() || "null".equals(str)) {
return true;
}
return false;
}
public static String xmlToJson(String xml) {
Document doc;
try {
doc = DocumentHelper.parseText(xml);
JSONObject json = new JSONObject();
dom4j2Json(doc.getRootElement(), json);
return json.toString();
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
}
模拟报文
<?xml version="1.0" encoding="utf-8"?>
<SERVICE>
<SERVICE_HEADER>
<apple>苹果大苹果小苹果好吃的不得了</apple>
</SERVICE_HEADER>
<SERVICE_BODY>
<INFORMATION>
<USER>
<NAME>姚明多大</NAME>
<AGE>?</AGE>
</USER>
<USER>
<NAME>姚明多高</NAME>
<AGE>反正比你高</AGE>
</USER>
</INFORMATION>
</SERVICE_BODY>
</SERVICE>
模板配置
根据需要自动配置
XMl转Map-map调用公共模板的更多相关文章
- 将多层级xml解析为Map
/** * 解析xml的工具类 * 1.将多层级xml解析为Map */ public class ParseXmlUtil { public static final String TAG = &q ...
- XML字符串转为Map集合
public class xmlToMapUtils { /** * xml字符串转为map集合 * @param xmlStr * @return */ public static Map<S ...
- Dom4j把xml转换成Map(固定格式)
/** * 可解析list * * @param fileName * @return * @throws Exception */ @SuppressWarnings("unchecked ...
- Dom4j把xml转换成Map(非固定格式)
将xml转换成Map,能够应对不用结构的xml,而不是只针对固定格式的xml.转换规则:1.主要是Map与List的互相嵌套2.同名称的节点会被装进List 示例: import java.util. ...
- java XML解析成Map
1.需要解析的文件.xml <?xml version="1.0" encoding="UTF-8"?> <request> <r ...
- 工具类--map 转成xml xml转成map
public class WxChatReq { /** * Map转换成XML * @param data * @return * @throws Exception */ public stati ...
- 笔记 freemark list标签迭代Map<Map<String,Object>集合排序问题
本博客是自己在学习和工作途中的积累与总结,仅供自己参考,也欢迎大家转载,转载时请注明出处. 工作中出现一个比较特殊的问题,在模板ftl文件中,一般用list迭代map 举例: 后台: // 传入的参数 ...
- 小程序公共模板template与公共js数据utils的引用实例
在小程序项目开发中,经常会遇到公共模板与公共js数据的调用,这里结合自己的项目为这一需求做一简单介绍 目录截图 现在是有一个评论版块需要在几个页面里共用 先将评论版块的wxml剔出来放在templat ...
- Angularjs调用公共方法与共享数据
这个问题场景是在使用ionic开发页面的过程中发现,多个页面对应的多个controller如何去调用公共方法,比如给ionic引入了toast插件,如何将这个插件的调用变成公共方法或者设置成工具类,因 ...
随机推荐
- Java Servlet 过滤器与 springmvc 拦截器的区别?
前言:在工作中,遇到需要记录日志的情况,不知道该选择过滤器还是拦截器,故总结了一下. servlet 过滤器 定义 java过滤器能够对目标资源的请求和响应进行截取.过滤器的工作方式分为四种 应用场景 ...
- Unix环境高级编程:守护进程
参考 Unix环境高级编程,第9,13章 介绍 守护进程就是Linux中使用ps aux那些一般以d结尾的程序,比如rsyslogd,sshd等,为daemon简称.他们是长期在后台执行的随终端关闭而 ...
- 常见Java问题二
1.什么是B/S架构?什么是C/S架构? B/S browser/server Web应用程序 C/S Client/Server 桌面应用程序 2.String str="www" ...
- apache2.2 +php7.3安装 编译安装
1.下载 http://archive.apache.org/dist/httpd/httpd-2.2.0.tar.gz tar -xvf httpd-2.2.0.tar.gz 2.安装 ./conf ...
- 洛谷P2881 [USACO07MAR]排名的牛Ranking the Cows(bitset Floyd)
题意 题目链接 Sol 显然如果题目什么都不说的话需要\(\frac{n * (n - 1)}{2}\)个相对关系 然后求一下传递闭包减掉就行了 #include<bits/stdc++.h&g ...
- js-ES6学习笔记-Class(5)
1.原生构造函数会忽略apply方法传入的this,也就是说,原生构造函数的this无法绑定,导致拿不到内部属性.比如,Array构造函数有一个内部属性[[DefineOwnProperty]],用来 ...
- Python 基于python实现的http接口自动化测试框架(含源码)
基于python实现的http+json协议接口自动化测试框架(含源码) by:授客 QQ:1033553122 欢迎加入软件性能测试交流 QQ群:7156436 由于篇幅问题,采用百度网 ...
- HBuilder开发iPad程序不能全屏显示的解决方法
HBuilder开发iPad程序不能全屏显示的解决方法: targets选择HBuilder=>Deployment Info=> devices选择Universal即可
- [我的阿里云服务器] —— FTP配置
前言: FTP是我们用来向服务器上传或者下载文件很重要的一个工具,特别是云服务器,无法使用外设传送文件. 所以下面我们就来配置一下FTP,但是FTP的21端口,通常也是黑客进攻的一个目标,所以需要小心 ...
- UWP开发细节记录:判断文件类型
StorageFile.ContentType 属性,是 string 类型,用来表示文件内容的 MIME 类型.例如,音乐文件可能有 "audio/mpeg" MIME 类型.( ...