Java 怎么被认为是特殊XML字符的转义字符

2019年8月2日23:25:54Java 怎么被认为是特殊XML字符的转义字符已关闭评论 850 1008字阅读3分21秒

1.简介

Java 怎么被认为是特殊XML字符的转义字符?——请看下文。

2.示例代码

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



import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String input = "tah1986.com";
        System.out.println(escapeXml(input));
    }

    private static final Pattern REPLACE_QUOTE = Pattern.compile("'");
    private static final Pattern REPLACE_DOUBLE_QUOTE = Pattern
            .compile("\"");
    private static final Pattern REPLACE_LESS_THAN = Pattern.compile("<");
    private static final Pattern REPLACE_GREATER_THAN = Pattern
            .compile(">");
    private static final Pattern REPLACE_AMP = Pattern.compile("&");

    
    public static String escapeXml(String input) {
        if (input == null) {
            return null;
        }

        Matcher matcher = REPLACE_DOUBLE_QUOTE.matcher(input);
        input = matcher.replaceAll(""");

        matcher = REPLACE_QUOTE.matcher(input);
        input = matcher.replaceAll("'");

        matcher = REPLACE_LESS_THAN.matcher(input);
        input = matcher.replaceAll("<");

        matcher = REPLACE_GREATER_THAN.matcher(input);
        input = matcher.replaceAll(">");

        matcher = REPLACE_AMP.matcher(input);
        input = matcher.replaceAll("&");

        return input;
    }
}

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