标签:去除xml文件的空格

  有些时候解析xml文件,要求读取的字符串必须是压缩后的xml文件,不能有多余的空格。考虑到在<>标签内包含空格和大于号的情况,写了以下的转换方式。

  传入的是压缩前的xml字符串,生成的是压缩后的字符串

private String convertFromXml(String str) {
    boolean flag = true;
    boolean quotesFlag = true;
    StringBuffer ans = new StringBuffer();
    String tmp = "";
    for (int i = 0; i < str.length(); i++) {
        if ('"' == str.charAt(i)) {
            ans.append(str.charAt(i));
            quotesFlag = !quotesFlag;
        } else if ('<' == str.charAt(i)) {
            tmp = tmp.trim();
            ans.append(tmp);
            flag = true;
            ans.append(str.charAt(i));
        } else if ('>' == str.charAt(i)) {
            if(quotesFlag){
                flag = false;
                ans.append(str.charAt(i));
                tmp = "";
            }else{
                ans.append("&gt;");
            }
        } else if (flag) {
            ans.append(str.charAt(i));
        } else {
            tmp += str.charAt(i);
        }
    }
    return ans.toString();
}

 

xml中的转义表

&lt;     <     小于号
&gt;     >     大于号
&amp;     &     和
&apos;     ’     单引号
&quot;     "     双引号

相关文章:

  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-12-23
  • 2022-01-06
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
相关资源
相似解决方案