将xml文件由格式化变为压缩字符串

  标签:去除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;     "     双引号

原文地址:https://www.cnblogs.com/acm-bingzi/p/xml.html