Java 怎么过滤XML字符串并转义不匹配标记中的尖括号

2019年8月2日23:26:29Java 怎么过滤XML字符串并转义不匹配标记中的尖括号已关闭评论 1,663 1672字阅读5分34秒

1.简介

Java 怎么过滤XML字符串并转义不匹配标记中的尖括号?——请看下文。

2.示例代码

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


import java.io.StringWriter;

public class Main{

    
    public static String makeFilteredString(String theString) {
        String t = theString;
        t = t.replaceAll("<br[\\s]*>", "<br />").replaceAll("</br[\\s]*>",
                "");
        t = t.replaceAll("<hr[\\s]*>", "<hr />").replaceAll("</hr[\\s]*>",
                "");
        t = t.replace("&", "&");
        String s = "";
        int left;
        int right;
        while (t.length() > 0) {
            left = t.indexOf("<");
            if (left == -1)
                return s + t.replace(">", ">");
            right = t.indexOf(">");
            if (right == -1)
                return s + t.replace("<", "<");
            if (right < left) {
                s += t.substring(0, right) + ">";
                t = t.substring(right + 1, t.length());
            } else {
                if (isItATag(t.substring(left, right + 1))) {
                    s += t.substring(0, right + 1);
                    t = t.substring(right + 1, t.length());
                } else {
                    s += t.substring(0, left) + "<";
                    t = t.substring(left + 1, t.length());
                }
            }
        }
        return s;
    }
    private static boolean isItATag(String s) {
        if (s.charAt(0) != '<')
            return false;
        boolean endTag = false;
        int i = StringUtil.skipWhitespace(s, 1);
        if (s.charAt(i) == '/') {
            endTag = true;
            i = StringUtil.skipWhitespace(s, i + 1);
        }
        if ((i = StringUtil.skipWord(s, i)) < 0)
            return false;
        i = StringUtil.skipWhitespace(s, i);
        if (s.charAt(i) == '>')
            return true;
        if (endTag)
            return false;
        while (i < s.length()) {
            if (s.charAt(i) == '/') {
                i = StringUtil.skipWhitespace(s, i + 1);
                if (s.charAt(i) == '>')
                    return true;
                return false;
            }
            if (s.charAt(i) == '>')
                return true;
            if ((i = skipAttribute(s, i + 1)) < 0)
                return false;
        }
        return false;
    }
    
    private static int skipAttribute(String xmlString, int i) {
        if ((i = StringUtil.skipWord(xmlString, i)) < 0)
            return -1;
        i = StringUtil.skipWhitespace(xmlString, i);
        if (xmlString.charAt(i) != '=')
            return -1;
        i = StringUtil.skipWhitespace(xmlString, i + 1);
        if (xmlString.charAt(i) != '\"')
            return -1;
        i = xmlString.indexOf('\"', i + 1);
        if (i < 0)
            return -1;
        i = StringUtil.skipWhitespace(xmlString, i + 1);
        return i;
    }
}

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