效果

<?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调用公共模板的更多相关文章

  1. 将多层级xml解析为Map

    /** * 解析xml的工具类 * 1.将多层级xml解析为Map */ public class ParseXmlUtil { public static final String TAG = &q ...

  2. XML字符串转为Map集合

    public class xmlToMapUtils { /** * xml字符串转为map集合 * @param xmlStr * @return */ public static Map<S ...

  3. Dom4j把xml转换成Map(固定格式)

    /** * 可解析list * * @param fileName * @return * @throws Exception */ @SuppressWarnings("unchecked ...

  4. Dom4j把xml转换成Map(非固定格式)

    将xml转换成Map,能够应对不用结构的xml,而不是只针对固定格式的xml.转换规则:1.主要是Map与List的互相嵌套2.同名称的节点会被装进List 示例: import java.util. ...

  5. java XML解析成Map

    1.需要解析的文件.xml <?xml version="1.0" encoding="UTF-8"?> <request> <r ...

  6. 工具类--map 转成xml xml转成map

    public class WxChatReq { /** * Map转换成XML * @param data * @return * @throws Exception */ public stati ...

  7. 笔记 freemark list标签迭代Map<Map<String,Object>集合排序问题

    本博客是自己在学习和工作途中的积累与总结,仅供自己参考,也欢迎大家转载,转载时请注明出处. 工作中出现一个比较特殊的问题,在模板ftl文件中,一般用list迭代map 举例: 后台: // 传入的参数 ...

  8. 小程序公共模板template与公共js数据utils的引用实例

    在小程序项目开发中,经常会遇到公共模板与公共js数据的调用,这里结合自己的项目为这一需求做一简单介绍 目录截图 现在是有一个评论版块需要在几个页面里共用 先将评论版块的wxml剔出来放在templat ...

  9. Angularjs调用公共方法与共享数据

    这个问题场景是在使用ionic开发页面的过程中发现,多个页面对应的多个controller如何去调用公共方法,比如给ionic引入了toast插件,如何将这个插件的调用变成公共方法或者设置成工具类,因 ...

随机推荐

  1. 看这一篇就够了,css选择器知识汇总

    对大多技术人员来说都比较熟悉CSS选择器,举一例子来说,假设给一个p标签增加一个类(class),可是执行后该class中的有些属性并没有起作用.通过Firebug查看,发现没有起作用的属性被覆盖了, ...

  2. JavaSE——序列化和反序列化

    序列化: 序列化对应写的操作.(读与写都是站在应用的角度上) 序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化.可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间 ...

  3. C#反射的一些经验[转载]

    写代码的时候经常需要分析已有类型的信息例如:分析现有类型自动生成类, 或者为现有的类自动增加一些功能总结了一点点经验以ClassA  a; 为例1. 通过typeof(ClassA) 或者 a.Get ...

  4. 关于Dynamics CRM 安装用户权限的说明

    做了这么多年的CRM项目,但发现部分客户的IT安全监管很严格,在CRM系统安装时,要求给出系统安排账号的权限. 这时小伙伴们 坚持不住了~~ 天天都是用域控的admin操作,这个时候问我要什么权限,于 ...

  5. Nginx的性能优化

    1.优化worker进程个数: 在高并发.高访问量的WEB服务场景,需要事先启动更多的nginx进程,以保证快速响应并处理大量并发用户的请求,优化nginx进程个数的配置项就是,在nginx.conf ...

  6. ConstraintLayout (约束布局)属性详情

    本文部分内容来自于网络,点击浏览原文 app:layout_constraintLeft_toLeftOf //Constrains the left side of a child to the l ...

  7. 团队项目第二阶段个人进展——Day1

    一.昨天工作总结 冲刺第一天,查看了第一阶段的代码 二.遇到的问题 写个的代码发现看不懂了 三.今日工作规划 重新设计页面布局

  8. Prometheus Node_exporter 之 Network Netstat ICMP

    Network Netstat ICMP /proc/net/snmp 1. ICMP Errors 1 type: GraphUnit: shortLabel: Messages out (-) / ...

  9. .Net 初步学习笔记之三---变量

    一.存储变量的语法: 变量类型  变量名: 变量名=值: “=”号:把等号右边的值赋值给等号左边的变量 二.常用的变量 1.整数类型 int  //只存整数,不能存小数 2.小数类型 double   ...

  10. SQL删除多列语句

    最近在写SQL过程中发现需要对一张表结构作调整(此处是SQL Server),其中需要删除多列,由于之前都是一条SQL语句删除一列,于是猜想是否可以一条语句同时删除多列,如果可以,怎么写法? 第一次猜 ...