1. 程式人生 > 其它 >處理 word 模板 xml 分割問題

處理 word 模板 xml 分割問題

  以 word 做模板時,文件中的字串在 xml 中可能被打散到多個節點。

  給出上下界字元(比如 {} ),去除中間無用的 dom 節點,使其之間的內容在 xml 中是連續完整的字串。

  用雙指標標出上下界後對其中的 dom 節點進行替換。

 public static void format(String inPath, String outPath, char beginFlag, char endFlag) throws Exception {
        InputStream in = new FileInputStream(inPath);
        OutputStream outputStream 
= new FileOutputStream(outPath); StringBuilder stringBuilder = new StringBuilder(); byte[] bytes = new byte[1024]; String pre = null; int len = -1; while ((len = in.read(bytes)) != -1) { byte[] bytes2 = new byte[len]; for (int k = 0; k < len; k++) bytes2[k] = bytes[k]; String content
= new String(bytes2, "UTF-8"); stringBuilder.append(content); } in.close(); int left = 0, right = 0; while (left < stringBuilder.length()) { if (right > left) { if (stringBuilder.charAt(right) == endFlag) { formatString(stringBuilder, left, right); right
++; left = right; } else right++; } else { if (stringBuilder.charAt(left) == beginFlag) right++; else { left++; right++; } } } String s = stringBuilder.toString(); if (s.contains("$")) s = s.replaceAll("\\$", ""); byte[] bytes1 = s.getBytes("UTF-8"); outputStream.write(bytes1, 0, bytes1.length); outputStream.flush(); outputStream.close(); } private static void formatString(StringBuilder stringBuilder, int left, int right) { boolean isDel = false; for (int i = left; i < right; i++) { if (isDel) { if (stringBuilder.charAt(i) == '>') isDel = false; stringBuilder.setCharAt(i, '$'); } else if (stringBuilder.charAt(i) == '<') { stringBuilder.setCharAt(i, '$'); isDel = true; } } }