Java 怎么转义XML

2019年8月2日23:22:48Java 怎么转义XML已关闭评论 410 667字阅读2分13秒

1.简介

Java 怎么转义XML?——请看下文。

2.示例代码

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


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

    private static char[] toBeEscaped = new char[] { '&', '<', '>', '"',
            '\'' };
    private static String[] escaped = new String[] { "&", "<",
            ">", """, "'" };

    public static String escapeForXML(String str) {
        StringBuilder sb = new StringBuilder(str.length());

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            boolean foundEscape = false;
            for (int j = 0; j < toBeEscaped.length; j++) {
                if (c == toBeEscaped[j]) {
                    sb.append(escaped[j]);
                    foundEscape = true;
                    break;
                }
            }

            if (foundEscape == false) {
                sb.append(c);
                foundEscape = false;
            }
        }
        return sb.toString();
    }
}

 
编程十万个怎么办