zoukankan      html  css  js  c++  java
  • 利用freemarker生成xml

    package com.mooc.freemarkerXML;
    
    import java.io.IOException;
    import java.io.StringWriter;
    import java.util.HashMap;
    import java.util.Map;
    
    import freemarker.template.Configuration;
    
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    
    
    public class XMLTest {
    
        public static Template getTemplate(String name){
            Configuration cfg = new Configuration();
            cfg.setClassForTemplateLoading(XMLTest.class, "/resources/");
            Template template = null;
            try {
                template = cfg.getTemplate(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return template;
        }
        
        public static String process(String templatefile, Map<String, Object> param) throws IOException, TemplateException,
         Exception{
             Template template = XMLTest.getTemplate(templatefile);
             StringWriter sw = new StringWriter();
             template.process(param, sw);
             return sw.toString();
        }
        public static void main(String[] args) {
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("id", "1");
            responseMap.put("name", "红楼梦");
            responseMap.put("author", "曹雪芹");
            responseMap.put("year", "1862");
            responseMap.put("price", "98");
            String resp = null;
            try {
                resp = XMLTest.process("book.ftl", responseMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(resp);
        }
    
    }

    book.ftl

    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
        <book id="${id}">
            <name>${name}</name>
            <author>${author}</author>
            <year>${year}</year>
            <price>${price}</price>
            <address><#if address??>${address}</#if></address>
        </book>
    </bookstore>

    XMLSerializer read()
  • 相关阅读:
    DOM对象模型接口规范中的四个基本接口
    js中几种实用的跨域方法原理详解(转)
    关于ie6/7下的z-index
    Mysql++学习(五)------专用SQL结构
    Mysql++学习(四)------模板查询
    Mysql++学习(三)------举个栗子
    Mysql++学习(二)------Mysql++简述
    Mysql++学习(一)------mysql编译安装
    epoll模型实例
    锁、页类型
  • 原文地址:https://www.cnblogs.com/james-roger/p/5438570.html
Copyright © 2011-2022 走看看