码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-30 21:05:07      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:color   for   from   必须   blog   append   span   private   trim   

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

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

标签:color   for   from   必须   blog   append   span   private   trim   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!