Java 怎么转义一个字符串,将&nn;、<、>、&、&、&替换为相应的字符

2019年7月31日23:38:13Java 怎么转义一个字符串,将&nn;、<、>、&、&、&替换为相应的字符已关闭评论 578 1324字阅读4分24秒

1.简介

Java 怎么转义一个字符串,将&nn;、<、>、&、&、&替换为相应的字符?——请看下文。

2.示例代码

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



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

    
    public static String unescapeXML(final String s) {
        char[] cc = s.toCharArray();
        int len = cc.length;
        StringBuffer sb = new StringBuffer();
        int pos;
        String esc;
        for (int i = 0; i < len; i++) {
            int c = cc[i];
            if (c == '&') {
                pos = findInArray(';', cc, i + 3);
                if (pos > -1) {
                    esc = new String(cc, i + 1, pos - i - 1);
                    if (esc.startsWith("#")) {
                        esc = esc.substring(1);
                        if (isValidCharacterValue(esc)) {
                            c = (char) Integer.parseInt(esc);
                            i = pos;
                        } else {
                            i = pos;
                            continue;
                        }
                    } else {
                        int tmp = unescape(esc);
                        if (tmp > 0) {
                            c = tmp;
                            i = pos;
                        }
                    }
                }
            }
            sb.append((char) c);
        }
        return sb.toString();
    }

    
    public static int findInArray(char needle, char[] haystack, int start) {
        for (int i = start; i < haystack.length; i++) {
            if (haystack[i] == ';')
                return i;
        }
        return -1;
    }

    
    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);
    }

    
    public static int unescape(String s) {
        if ("apos".equals(s))
            return '\'';
        if ("quot".equals(s))
            return '"';
        if ("lt".equals(s))
            return '<';
        if ("gt".equals(s))
            return '>';
        if ("amp".equals(s))
            return '&';
        return -1;
    }
}

 
继续阅读