Java 怎么通过将XML转义序列转换回正常字符来取消对字符串的转义

2019年8月3日23:23:43Java 怎么通过将XML转义序列转换回正常字符来取消对字符串的转义已关闭评论 418 1504字阅读5分0秒

1.简介

Java 怎么通过将XML转义序列转换回正常字符来取消对字符串的转义?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

     


public class Main {
    public static void main(String[] argv) throws Exception {
        String string = "tah1986.com";
        System.out.println(unescapeFromXML(string));
    }

    
    public static final String unescapeFromXML(String string) {
        string = replace(string, "<", "<");
        string = replace(string, ">", ">");
        string = replace(string, """, "\"");
        return replace(string, "&", "&");
    }

    
    public static final String replace(String line, String oldString,
            String newString) {
        if (line == null) {
            return null;
        }
        int i = 0;
        if ((i = line.indexOf(oldString, i)) >= 0) {
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = line.indexOf(oldString, i)) > 0) {
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }

    
    public static final String replace(String line, String oldString,
            String newString, int[] count) {
        if (line == null) {
            return null;
        }
        int i = 0;
        if ((i = line.indexOf(oldString, i)) >= 0) {
            int counter = 0;
            counter++;
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = line.indexOf(oldString, i)) > 0) {
                counter++;
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            count[0] = counter;
            return buf.toString();
        }
        return line;
    }
}

 
继续阅读