Java 怎么用适当的XML代码转义字符串

2019年7月30日22:59:39Java 怎么用适当的XML代码转义字符串已关闭评论 390 1001字阅读3分20秒

1.简介

Java 怎么用适当的XML代码转义字符串?——请看下文。

2.示例代码

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

 


public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "tah1986.com";
        boolean onlyASCII = true;
        System.out.println(escapeXML(s, onlyASCII));
    }

    
    public static String escapeXML(final String s, final boolean onlyASCII) {
        char cc[] = s.toCharArray();
        int len = cc.length;
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < len; ++k) {
            int c = cc[k];
            switch (c) {
            case '<':
                sb.append("<");
                break;
            case '>':
                sb.append(">");
                break;
            case '&':
                sb.append("&");
                break;
            case '"':
                sb.append(""");
                break;
            case '\'':
                sb.append("'");
                break;
            default:
                if (isValidCharacterValue(c)) {
                    if (onlyASCII && c > 127)
                        sb.append("&#").append(c).append(';');
                    else
                        sb.append((char) c);
                }
            }
        }
        return sb.toString();
    }

    
    public static boolean isValidCharacterValue(String s) {
        try {
            int i = Integer.parseInt(s);
            return isValidCharacterValue(i);
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    
    public static boolean isValidCharacterValue(int c) {
        return (c == 0x9 || c == 0xA || c == 0xD || c >= 0x20
                && c <= 0xD7FF || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000
                && c <= 0x10FFFF);
    }
}

 
继续阅读
编程十万个怎么办