Java 怎么返回将所有非ASCII和<,&,>编码为XML数字实体的字符串

2019年8月9日22:18:30Java 怎么返回将所有非ASCII和<,&,>编码为XML数字实体的字符串已关闭评论 620 984字阅读3分16秒

1.简介

Java 怎么返回将所有非ASCII和<,&,>编码为XML数字实体的字符串?——请看下文。

2.示例代码

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



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

    
    public static String protectSpecialCharacters(
            String originalUnprotectedString) {
        if (originalUnprotectedString == null) {
            return null;
        }
        boolean anyCharactersProtected = false;

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < originalUnprotectedString.length(); i++) {
            char ch = originalUnprotectedString.charAt(i);

            boolean controlCharacter = ch < 32;
            boolean unicodeButNotAscii = ch > 126;
            boolean characterWithSpecialMeaningInXML = ch == '<'
                    || ch == '&' || ch == '>' || ch == '"';

            if (characterWithSpecialMeaningInXML || unicodeButNotAscii
                    || controlCharacter) {
                stringBuffer.append("&#" + (int) ch + ";");
                anyCharactersProtected = true;
            } else {
                stringBuffer.append(ch);
            }
        }
        if (anyCharactersProtected == false) {
            return originalUnprotectedString;
        }

        return stringBuffer.toString();
    }
}

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