Java 怎么给定一个字符串,用相应的XML特殊字符替换XML实体的所有实例

2019年8月3日23:34:46Java 怎么给定一个字符串,用相应的XML特殊字符替换XML实体的所有实例已关闭评论 579 821字阅读2分44秒

1.简介

Java 怎么给定一个字符串,用相应的XML特殊字符替换XML实体的所有实例?——请看下文。

2.示例代码

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


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

    
    public static String unescapeForXML(String string) {
        string = substitute(string, "&", "&");
        string = substitute(string, """, "\"");
        string = substitute(string, "<", "<");
        string = substitute(string, ">", ">");
        string = substitute(string, "
", "\n");
        string = substitute(string, "
", "\r");
        return string;
    }

    
    public static String substitute(String string, String pattern,
            String replacement) {
        int start = string.indexOf(pattern);

        while (start != -1) {
            StringBuffer buffer = new StringBuffer(string);
            buffer.delete(start, start + pattern.length());
            buffer.insert(start, replacement);
            string = new String(buffer);
            start = string.indexOf(pattern, start + replacement.length());
        }

        return string;
    }
}

 
继续阅读