Does the string contain XML special characters - Java XML

Java examples for XML:XML Encoding

Description

Does the string contain XML special characters

Demo Code



public class Main{
    public static void main(String[] argv) throws Exception{
        String input = "java2s.com";
        System.out.println(containsXmlEscapeCharacters(input));
    }//w  ww . j  a va2s  . c  om
    private static final StringPair[] XML_SPECIAL_STRINGS = {
            new StringPair("<", "&lt;"), new StringPair(">", "&gt;"),
            new StringPair("\"", "&quot;"), new StringPair("&", "&amp;"),
            new StringPair("\'", "&#039;") // TODO why ' is escaped with \?
    };
    /**
     * Does the string contain XML special characters
     *
     * @param input Input string
     * @return True if input contains XML special characters. Otherwise false.
     */
    public static boolean containsXmlEscapeCharacters(String input) {
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            for (StringPair sp : XML_SPECIAL_STRINGS) {
                if (sp.getPlain().equals(Character.toString(c))) {
                    return true;
                }
            }
        }
        return false;
    }
}

Related Tutorials