xml字符串格式化

前端之家收集整理的这篇文章主要介绍了xml字符串格式化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. /**
  2. <b><b> \r\n(+\t)
  3. </b><b> \r\n
  4. </b></b> \r\n(-\t)
  5. /><b> \r\n
  6. /></b> \r\n(-\t)
  7. */
  8. public static void show(String xml) {
  9. Matcher mth = Pattern.compile("(?:<\\w+>\\s*<\\w+|</\\w+>\\s*<.|/>\\s*<.)").matcher(xml);
  10. int count = 0;
  11. StringBuffer sb = new StringBuffer();
  12. char[] cs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t".tocharArray();
  13. int lastEnd = 0;
  14. while (mth.find(lastEnd)) {
  15. try {
  16. String str = mth.group();
  17. int idx2 = str.indexOf('<',1);
  18. if (str.charAt(0) == '<' && str.charAt(1) != '/') {
  19. count++;
  20. } else if (str.charAt(0) == '<' && str.charAt(1) == '/') {
  21. if (str.charAt(idx2 + 1) == '/') {
  22. count--;
  23. }
  24. } else if (str.charAt(0) == '/') {
  25. if (str.charAt(idx2 + 1) == '/') {
  26. count--;
  27. }
  28. }
  29. sb.append(xml,lastEnd,mth.start() + str.indexOf('>') + 1).append("\r\n").append(cs,count);
  30. lastEnd = mth.start() + idx2;
  31. } catch (Exception e) {
  32. throw new RuntimeException(count + "," + lastEnd + "," + sb + "--",e);
  33. }
  34. }
  35. sb.append(xml,xml.length());
  36. System.out.println(sb);
  37. }


(?:) 非获取匹配,不进行存储供以后使用,预查消耗字符

(?=) 正向预查,预查不消耗字符,

猜你在找的XML相关文章