Java 怎么将原始字符转换为XML转义字符

2019年7月30日22:59:43Java 怎么将原始字符转换为XML转义字符已关闭评论 430 1017字阅读3分23秒

1.简介

Java 怎么将原始字符转换为XML转义字符?——请看下文。

2.示例代码

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



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

    
    public static String escapeXML(String rawContent, String charset,
            boolean isNoLines) {
        if (rawContent == null)
            return ""; 
        else {
            StringBuffer sb = new StringBuffer();

            for (int i = 0; i < rawContent.length(); i++) {
                char ch = rawContent.charAt(i);
                if (ch == '\'')
                    sb.append("'"); 
                else if (ch == '&')
                    sb.append("&"); 
                else if (ch == '"')
                    sb.append("""); 
                else if (ch == '<')
                    sb.append("<"); 
                else if (ch == '>')
                    sb.append(">"); 
                else if (ch > '~' && charset != null
                        && charSetImpliesAscii(charset))
                    
                    
                    sb.append("&#x" + Integer.toHexString(new Character(ch).hashCode()).toUpperCase() + ";"); 
                else if (isNoLines) {
                    if (ch == '\r')
                        sb.append("
"); 
                    else if (ch != '\n')
                        sb.append(ch);
                } else
                    sb.append(ch);
            }
            return sb.toString();
        }
    }

    public static boolean charSetImpliesAscii(String charset) {
        return charset.equals("ISO-8859-1") || charset.equals("US-ASCII"); 
    }
}

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