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())+1;
                    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>

模板配置

根据需要自动配置
原文地址:https://www.cnblogs.com/mutong1228/p/9010384.html