# 简介
生成复杂的 word 文档需要使用 xml 格式的 word 模板,但是另存为 xml 文件的 word 文件格式比较杂乱。现提供一个格式化 xml 的工具类,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package xxx.util;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.file.FileAppender; import cn.hutool.core.io.file.FileReader;
import java.util.List;
public class WordConvertXmlHandle {
public static void main(String[] args) { FileReader fileReader = new FileReader("D:\\mb.xml"); List<String> strings = fileReader.readLines(); FileAppender appender = new FileAppender(FileUtil.newFile("D:\\mb.ftl"), 16, true); for (String string : strings) { if (!string.contains("$")) { appender.append(string); continue; } string = string.replaceAll("\\$", "#\\$"); String[] ss = string.split("#"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ss.length; i++) { String s1 = ss[i]; if (!s1.startsWith("$")) { sb.append(s1); continue; } int i1 = s1.lastIndexOf("}"); String substr = s1.substring(0, i1 + 1); sb.append(substr.replaceAll("<[^>]+>", "")); sb.append(s1.substring(i1 + 1)); } appender.append(sb.toString()); } appender.flush(); appender.toString(); } }
|