问题描述
如下的一个模板文件,如何写对应的代码(java),请知道的指点下<?xml version="1.0" encoding="UTF-8"?><File> <Head> <FileLength>00001849</FileLength> <FileTime>20130817112307</FileTime> <KeyIndex>0</KeyIndex> </Head> <Body> <#list Data as Data> <Data> <IMSI>${Data.IMSI}</IMSI> <#list CardOperTypes as CardOperTypes> <CardOperTypes><CardOperType CardOperTypeId="${CardOperTypes.CardOperTypeId}" CardOperTypeName="${CardOperTypes.CardOperTypeName}" /><CardOperType CardOperTypeId="${CardOperTypes.CardOperTypeIdConvert}" CardOperTypeName="${CardOperTypes.CardOperTypeName}" /> </CardOperTypes> </#list> </Data> </#list> </Body></File> 问题补充:下面我写的测试类;把模板中的 <#list CardOperTypes as CardOperTypes> <CardOperTypes> <CardOperType CardOperTypeId="${CardOperTypes.CardOperTypeId}" CardOperTypeName="${CardOperTypes.CardOperTypeName}" /> <CardOperType CardOperTypeId="${CardOperTypes.CardOperTypeIdConvert}" CardOperTypeName="${CardOperTypes.CardOperTypeName}" /> </CardOperTypes> </#list> 去掉是可以的,但加上就不行了,不知哪里有问题public class Test {@SuppressWarnings("unchecked")public static void main(String[] args) {Configuration cfg = new Configuration();File tpl = new File("D://work");//加载模板文件的目录try {cfg.setDirectoryForTemplateLoading(tpl);Map params = getParams();Template requestTemplate = cfg.getTemplate("1.xml");StringWriter out = new StringWriter();requestTemplate.process(params, out);System.out.println(out.toString());} catch (Exception e1) {e1.printStackTrace();}}private static Map getParams() {Map params = new HashMap();params.put("Head", head());params.put("Quantity", 2);params.put("Data", data());return params;}private static List<Map> data() {List<Map> data = new ArrayList<Map>();for(int i=0;i<1;i++){Map datadetail=new HashMap();datadetail.put("IMSI","460030400011007");datadetail.put("CARD", CardOperTypes());data.add(datadetail);}return data;}private static List<Map> CardOperTypes() {List<Map> CardOperTypes = new ArrayList<Map>();/*for(int i=0;i<4;i++){Map datadetail=new HashMap();datadetail.put("CardOperType",map());CardOperTypes.add(datadetail);}*/for(int i=0;i<1;i++){Map datadetail=new HashMap();datadetail.put("IMSIS","460030400011007");CardOperTypes.add(datadetail);}return CardOperTypes;}private static Map head() {Map head = new HashMap();head.put("FileVersion", "010000"); return head;}}
解决方案
需要把Data 这个集合放到变量里面,可以参考http://blog.csdn.net/kkdelta/article/details/7220252