使用XML模板填充数据

前端之家收集整理的这篇文章主要介绍了使用XML模板填充数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

java 代码如下:

  1. public class GeneralXML {
  2. public static String readFile(String filePath) {
  3. StringBuffer sb = new StringBuffer();
  4. File file = new File(filePath);
  5. FileReader fr = null;
  6. try {
  7. fr = new FileReader(file);
  8. } catch (FileNotFoundException e) {
  9. e.printStackTrace();
  10. }
  11. BufferedReader br = new BufferedReader(fr);
  12.  
  13. String strLine = "";
  14. try {
  15. while ((strLine = br.readLine()) != null) {
  16. sb.append(strLine);
  17. sb.append("\n");
  18. }
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. } finally {
  22. try {
  23. fr.close();
  24. br.close();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. return sb.toString();
  30. }
  31. public static void main(String[] args) {
  32. final String head = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
  33. final String root_start = "<root>";
  34. final String root_end = "</root>";
  35. StringBuffer sb = new StringBuffer();
  36. sb.append(head);
  37. sb.append(root_start);
  38. MessageFormat mf = new MessageFormat(readFile("src/main/resources/template.xml"));
  39. sb.append(mf.format(new Object[] { "11","12","13","14"}));
  40. sb.append(mf.format(new Object[] { "21","22","23","24"}));
  41. sb.append(root_end);
  42. System.out.println(sb.toString());
  43. }
  44. }

xml模板如下:
  1. <study name="{0}">
  2. <one>{1}</one>
  3. <two>{2}</two>
  4. <three>{3}</three>
  5. </study>


在实际应用中,我们可以将代码中的xml的头和尾都放在xml模板中,而代码就可以省略 StringBuffer了

猜你在找的XML相关文章