我的思维停留在,使用freemarker来将.ftl文件生成静态html页面。今天用到了,来读取xml模板,并生成xml模板。
上代码:
package xxx;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public freemarkerTest class {
/** 随着类加载而加载的静态代码块 */
static {
//freemarker的配置类
Configuration configuration = new Configuration();
//因为是springBoot项目,指定模板在templates路径下
configuration.setClassForTemplateLoading(configuration.getClass(), "/templates");
try {
//获取模板类
TEMPLATE = configuration.getTemplate("/freemarker.xml", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
LOGGER.warn("模板加载解析异常:" + e);
}
}
//生成xml
public void createXML(){
//给定xml文件输出路径
Writer writer = new FileWriter("E:/demo.xml");
//按照用法,来个map集合
Map<String, String> map = new HashMap<String, String>();
map.put("guid","GIHIHO-OJUYU-HKOO";
map.put("version","1.0.0");
map.put("hello","hello freemarker");
//调用process方法
TEMPLATE.process(map,writer);
}
}
//模板xml文件 <?xml version="1.0" encoding="UTF-8"?> <ceb:CEB511Message guid="${guid}" version="${version}" xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <ceb:Logistics> <ceb:LogisticsHead> <ceb:guid>${guid}</ceb:guid> <ceb:appType>${hello}</ceb:appType> </ceb:LogisticsHead> </ceb:Logistics> </ceb:CEB511Message>
//结果xml文件 <?xml version="1.0" encoding="UTF-8"?> <ceb:CEB511Message guid="GIHIHO-OJUYU-HKOO" version="1.0.0" xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <ceb:Logistics> <ceb:LogisticsHead> <ceb:guid>GIHIHO-OJUYU-HKOO</ceb:guid> <ceb:appType>hello freemarker</ceb:appType> </ceb:LogisticsHead> </ceb:Logistics> </ceb:CEB511Message>
freemarker不仅可以转换ftl文件,还可以转换xml,jsp文件
小小手掌,大大力量,小小工具,大大场景,
欢迎指正