利用Freemarker引擎进行transform

package donny;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TestFreeMarker extends XXXXXXXXXXIntegrationTest{

/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws TemplateException
*/
@Test
public void testOne() throws ParserConfigurationException, SAXException, IOException, TemplateException {
/**1. get Document Object**/
// InputStream in = new FileInputStream("e:/temp/free.xml");
// InputSource ins=new org.xml.sax.InputSource(in);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Document d = builder.parse("e:/temp/free.xml");
// show(DOMUtils.text(d));
// show(DOMUtils.text(d.getDocumentElement()));

/**2. get Temp Object**/
Configuration cfg = new Configuration();
cfg.setEncoding(Locale.getDefault(), "UTF-8");
cfg.setClassForTemplateLoading(TestFreeMarker.class, "");
Template temp = cfg.getTemplate("free.ftl");
// Template temp = cfg.getTemplate("E:/temp/free.ftl");
show(temp.getName());



/**4. read file from arch**/
// File templateFile = dataFolder.getActualFile("osi/bcbsma/appTemplate.xml");
// Document template = builder.parse(templateFile);

File free = new File("e:/temp/free.xml");

FileInputStream fis = new FileInputStream(free);

String targetString = FileUtils.readFileToString(free);
String header = "<e:test xmlns:e=\"http://example.com/ebook\">";
String footer = "</e:test>";
targetString = header + targetString + footer;
StringReader sr = new StringReader(targetString);

// StringReader sr = new StringReader()
// TemplateCache.getAllSubElements(temp).get(0)

/**3. **/

Map<String, NodeModel> root = new HashMap<String, NodeModel>();
root.put("doc", freemarker.ext.dom.NodeModel.parse(new InputSource(sr)));

java.io.StringWriter w =new StringWriter();
temp.process(root, w);
System.out.println(w.toString());

}

private static void show(String target){
System.out.println(target);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值