使用XML模板填充数据
发布时间:2020-12-16 08:43:06 所属栏目:百科 来源:网络整理
导读:java 代码如下: public class GeneralXML {public static String readFile(String filePath) {StringBuffer sb = new StringBuffer();File file = new File(filePath);FileReader fr = null;try {fr = new FileReader(file);} catch (FileNotFoundException
java 代码如下: public class GeneralXML { public static String readFile(String filePath) { StringBuffer sb = new StringBuffer(); File file = new File(filePath); FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader br = new BufferedReader(fr); String strLine = ""; try { while ((strLine = br.readLine()) != null) { sb.append(strLine); sb.append("n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static void main(String[] args) { final String head = "<?xml version="1.0" encoding="UTF-8" standalone="no"?>n"; final String root_start = "<root>"; final String root_end = "</root>"; StringBuffer sb = new StringBuffer(); sb.append(head); sb.append(root_start); MessageFormat mf = new MessageFormat(readFile("src/main/resources/template.xml")); sb.append(mf.format(new Object[] { "11","12","13","14"})); sb.append(mf.format(new Object[] { "21","22","23","24"})); sb.append(root_end); System.out.println(sb.toString()); } } xml模板如下: <study name="{0}"> <one>{1}</one> <two>{2}</two> <three>{3}</three> </study> 在实际应用中,我们可以将代码中的xml的头和尾都放在xml模板中,而代码就可以省略 StringBuffer了 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |