将对象值写入XML模板中的方法

前端之家收集整理的这篇文章主要介绍了将对象值写入XML模板中的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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



一、报文模板:cancel_hesitation_request.xml

<?xml version="1.0" encoding="GBK"?>
<REQUEST>
	<DIST>
		<SEAT_DEPT>${seatDept}</SEAT_DEPT>
		<SEAT_CODE>${seatCode}</SEAT_CODE>
		<INSU>${insu}</INSU>
	</DIST>
	<BUSI>
         <CATE>11</CATE><!--固定-->
		<SUBJECT>${subject}</SUBJECT><!--固定-->
		<TRSDATE>${traDate}</TRSDATE><!-- 交易日期 -->
		<TRANS>${trans}</TRANS> 
		<CONTENT>
		    <VALIDATETIME>${validateTime}</VALIDATETIME>
			<POLICYCODE>${policyNo}</POLICYCODE >
			<BIZCHANNEL>11</BIZCHANNEL>
			<SERVICEID>${serviceId}</SERVICEID >
		        <TRANS_DETAILS>
			       <TRANS_INFO>
		             <PRODUCTNUM>${productNum}</PRODUCTNUM>
					 <WITHDRAWMONEY>${withdrawMoney}</WITHDRAWMONEY>
		           </TRANS_INFO>
		        </TRANS_DETAILS>
		</CONTENT>
	</BUSI>
</REQUEST>


方法一:使用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<String,Object> context = new HashMap<String,Object>();
			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",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 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,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",request.getTraDate()));
		
		context.put("trans",request.getTrans());
		context.put("validateTime",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;
	}
原文链接:https://www.f2er.com/xml/299203.html

猜你在找的XML相关文章