Java 怎么将XML字符:&转为&amp;<转为&lt;>转为&gt;“转为&034;’转为&039;

2019年8月2日23:25:10Java 怎么将XML字符:&转为&amp;<转为&lt;>转为&gt;“转为&034;’转为&039;已关闭评论 874 712字阅读2分22秒

1.简介

Java 怎么将XML字符:&转为&amp;<转为&lt;>转为&gt;“转为&034;'转为&039;?——请看下文。</to&lt;>

2.示例代码

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



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

    
    public static final int HIGHEST_SPECIAL = '>' + 1;
    
    public static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL][];

    
    public static String replaceXmlChar(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(str.length() * 2);
        for (int i = 0, len = str.length(); i < len; i++) {
            char c = str.charAt(i);
            if (c < HIGHEST_SPECIAL) {
                char[] escaped = specialCharactersRepresentation[c];
                if (escaped != null) {
                    sb.append(escaped);
                } else {
                    sb.append(c);
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}