java xml模板读写_将对象值写入XML模板中的方法 | 学步园

本文介绍了在Java中如何使用Freemarker和Velocity库填充XML模板,详细展示了两种方法的代码实现,包括设置模板参数、转换日期格式及生成最终的XML字符串。
摘要由CSDN通过智能技术生成

项目中经常会用到xml模板,如邮件、短信等,在java中填充xml模板,方法很多,这边介绍两个方法(jaxb不算),用到freemarker.template.Template和org.apache.velocity.VelocityContext

一、报文模板:cancel_hesitation_request.xml

${seatDept}

${seatCode}

${insu}

11

${subject}

${traDate}

${trans}

${validateTime}

${policyNo}

11

${serviceId}

${productNum}

${withdrawMoney}

方法一:使用freemarker.template.Template和org.springframework.ui.freemarker.FreeMarkerTemplateUtils

private String getCancelRequestMsg(CancelRequestDTO request) {

// 定义局部变量

String templatePath = "/template/cancel/"; // 报文模板路径

String templateFileName = "cancel_hesitation_request.xml"; // 模板文件名

String requestXml = "";

// 构建请求报文,并转换成报文字符串

Configuration config = new Configuration();

try {

//config.setDirectoryForTemplateLoading(new File(templatePath));

//Template template=config.getTemplate(templateFileName);

config.setClassForTemplateLoading(getClass(), "/");

Template template = config.getTemplate("template/cancel/cancel_hesitation_request.xml","GBK");// 报文模板

// 设置模板参数

Map context = new HashMap();

context.put("seatDept", request.getSeatDept());

context.put("seatCode", request.getSeatCode());

context.put("insu", request.getInsu());

context.put("subject", request.getSubject());

context.put("traDate", DateUtils.dateToString("yyyyMMdd", request.getTraDate()));

//

context.put("trans", request.getTrans());

context.put("validateTime", DateUtils.dateToString("yyyyMMdd",request.getValidateTime()));

context.put("policyNo", request.getPolicyNo());

context.put("serviceId", request.getServiceId());

context.put("productNum", request.getProductNum().get(0));

context.put("withdrawMoney", request.getWithdrawMoney().get(0)==null ? "" : request.getWithdrawMoney().get(0).toString());

requestXml = FreeMarkerTemplateUtils.processTemplateIntoString(template,context);

LogTool.inf(this.getClass(), "getCancelRequest is: " + requestXml);

System.out.println(this.getClass()+ " getCancelRequest is: \n" + requestXml);

if (requestXml == null || "".equals(requestXml)) {

errorLogTool.addErrorLog("填充模板出错,模板路径:" + templatePath

+ templateFileName, ConstantTool.ErrorTemplateFill);

return null;

}

} catch (IOException e) {

e.printStackTrace();

} catch (TemplateException e) {

e.printStackTrace();

}

// 返回报文字符串

return requestXml;

}

方法二:使用org.apache.velocity.VelocityContext和org.apache.velocity.Template

1、封装的TemplateTool.java,用于填充模板

import java.io.PrintStream;

import java.io.StringReader;

import java.io.StringWriter;

import java.net.URL;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;

import org.apache.velocity.Template;

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.VelocityEngine;

public class TemplateTool

{

public static String fill(VelocityContext context, String tmdir, String tmFile)

{

String result = "";

try {

Properties p = new Properties();

p.setProperty("file.resource.loader.path", tmdir);

VelocityEngine ve = new VelocityEngine();

ve.init(p);

Template t = ve.getTemplate(tmFile);

StringWriter writer = new StringWriter();

t.merge(context, writer);

result = writer.toString();

writer.close();

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

public static String fill(VelocityContext context, String tmdir, String tmFile, String inputEncode, String ouputEncode)

{

String result = "";

try {

Properties p = new Properties();

p.setProperty("file.resource.loader.path", tmdir);

p.setProperty("ISO-8859-1", "UTF-8");

p.setProperty("input.encoding", inputEncode);

p.setProperty("output.encoding", ouputEncode);

VelocityEngine ve = new VelocityEngine();

ve.init(p);

Template t = ve.getTemplate(tmFile);

StringWriter writer = new StringWriter();

t.merge(context, writer);

result = writer.toString();

writer.close();

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

public static String fill(VelocityContext context, String templateString)

{

String result = "";

try

{

VelocityEngine ve = new VelocityEngine();

ve.init();

StringWriter writer = new StringWriter();

StringReader reader = new StringReader(templateString);

ve.evaluate(context, writer, "temp", reader);

result = writer.toString();

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

public static String test(int i)

{

return "array:" + i;

}

}

2、具体写入的方法,其中调用TemplateTool.fill()方法。

private String getCancelRequestMsg(CancelRequestDTO request) {

// 定义局部变量

String templatePath = "/template/cancel/"; // 报文模板路径

String templateFileName = "cancel_hesitation_request.xml"; // 报文模板文件名

String requestXml = "";

// 构建请求报文,并转换成报文字符串

VelocityContext context = new VelocityContext();

context.put("seatDept", request.getSeatDept());

context.put("seatCode", request.getSeatCode());

context.put("insu", request.getInsu());

context.put("subject", request.getSubject());

context.put("traDate", DateUtils.dateToString("yyyyMMdd", request.getTraDate()));

context.put("trans", request.getTrans());

context.put("validateTime", DateUtils.dateToString("yyyyMMdd",request.getValidateTime()));

context.put("policyNo", request.getPolicyNo());

context.put("serviceId", request.getServiceId());

context.put("productNum", request.getProductNum().get(0));

context.put("withdrawMoney", request.getWithdrawMoney().get(0));

requestXml = TemplateTool.fill(context, this.getClass().getResource(

templatePath).getPath(), templateFileName, "GBK", "GBK");

LogTool.inf(this.getClass(), "getCancelRequest is: " + requestXml);

if (requestXml == null || "".equals(requestXml)) {

errorLogTool.addErrorLog("填充模板出错,模板路径:" + templatePath

+ templateFileName, ConstantTool.ErrorTemplateFill);

return null;

}

// 返回报文字符串

return requestXml;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值