效果

<?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. EF数据库优先模式(一)

    C#中EF模式,讲述个人在做项目时用到的一些思路以及方法 EF数据模型有三种方式,database优先,model优先,Code优先,个人在做项目时用到的是database优先,以后再说其他的方式 d ...

  2. macbook 外接显示器黑屏,不显示

    我的mac本有点老了,11年底的那款 整了个显示器,刚开始连上没问题,后来开机状态拔了雷电线,再插  或者关机后莫名的原因再启动,显示器黑屏 网上好多方法都不行,自己总结了一个方法 拔掉连接线,关闭m ...

  3. php+xml有什么用

    很多招聘网上找php程序员的时候都说要懂xml,这个xml+php在web网站开发方面到底有什么应用呢,希望有知道的朋友能给我具体说说,谢谢了! 我说的是在网站中的实际应用有哪些,不是网上抄的xml的 ...

  4. Javascript 随机数函数 学习之二:产生服从正态分布随机数

    一.为什么需要服从正态分布的随机函数 一般我们经常使用的随机数函数 Math.random() 产生的是服从均匀分布的随机数,能够模拟等概率出现的情况,例如 扔一个骰子,1到6点的概率应该相等,但现实 ...

  5. [USACO18FEB]Slingshot

    题意可化为: 在二维平面中有n个点,坐标为\((x_i,y_i)\),点权为\(t_i\). 现有m个询问,每次给定点\((x,y)\),求\(\min\{|x-x_i|+|y-y_i|+t_i,|y ...

  6. thymeleaf标签使用方法总结

    https://blog.csdn.net/quuqu/article/details/52511933 常用th标签https://www.cnblogs.com/suncj/p/4030393.h ...

  7. 从零开始学习html(十一)CSS盒模型——上

    一.元素分类 在CSS中,html中的标签元素大体被分为三种不同的类型:块状元素.内联元素(又叫行内元素)和内联块状元素. 常用的块状元素有: <div>.<p>.<h1 ...

  8. IntelliJ idea 备份与恢复

    为了防止突然断电或者电脑突然关机导致idea恢复出厂设置,需要定期备份配置. 一.备份 File---Export Settings 将settings.jar 文件导入到C:\Users\xutin ...

  9. OSGI企业应用开发(十三)OSGI Web应用开发(二)

    上篇文章介绍了OSGI Web应用的两种开发模式,并把Jetty应用服务器以Bundle的形式整合到Equinox容器中,已这种模式开发Web应用,所有的应用程序资源,例如Servlet.JSP.HT ...

  10. PeopleSoft面试题...

    Q1:PS发出的邮件附件名字中中文字符乱码在哪设置? A1: 分为APP和PROCESS两个配置文件,分别在psprcs.cfg 和 psappsrv.cfg 中 SMTP Settings设置. 评 ...