效果

<?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. SpringBoot启动加载类ApplicationRunner

    SpringBoot启动加载类ApplicationRunner 有时希望项目在启动的时候加载一些系统参数,就要用到ApplicationRunner ApplicationRunner是一个接口,我 ...

  2. linux_shell_字符串

    字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号. 但是单引号和双引号是有区别的: 单引号: 单引号里的任何 ...

  3. 用node.js模拟服务器和客户端

    服务器 代码 var net = require("net") var server = net.createServer(); server.listen(12306," ...

  4. jquery判断浏览器的内核

    <script type='text/javascript'> $(function(){ if($.browser.msie) { alert("IE浏览器"); } ...

  5. 学习笔记(4)——实验室集群管理结点IP配置

    经过验证,集群管理结点mgt的IP配置应为如下所示: [root@mgt zmq]# ifconfig//外部网卡 eth0 Link encap:Ethernet HWaddr 5C:F3:FC:E ...

  6. Wireshark wireshake数据包分割及捕包过滤器介绍

    wireshake数据包分割及捕包过滤器介绍 by:授客 QQ:1033553122 wireshake自带工具editcap分割数据包 操作: 进入到目录,然后 editcap.exe -c < ...

  7. mysql如何修改开启允许远程连接

    关于mysql远程连接的问题,大家在公司工作中,经常会遇到mysql数据库存储于某个人的电脑上,大家要想连接mysql服务,装有mysql服务的电脑就必须开启远程连接 第一步,用dos连接上你的数据库 ...

  8. python websocket client 使用

    import websocket ws = websocket.WebSocket() ws.connect("xx.xx.xx") ws.send("string&qu ...

  9. LeetCode题解之 Search in a Binary Search Tree

    1.题目描述 2.问题分析 利用递归遍历二叉查找树. 3.代码 TreeNode* searchBST(TreeNode* root, int val) { if (root == NULL) ret ...

  10. 获取指定时间的Date对象,IE和Chrome的区别(兼容IE)

    网上的大多教程都是 new Date("2016-08-03 00:00:00"); 其实这是Chrome的写法,在IE中并不起作用,在IE中应为 new Date("2 ...