escapes & < > " ' characters to & < $gt; " ' - Java XML

Java examples for XML:XML String Escape

Description

escapes & < > " ' characters to & < $gt; " '

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        System.out.println(xmlEsc(str));
    }/*  w  ww.ja v  a 2  s  .  c om*/

    /**
     * escapes & < > " ' characters to &amp; &lt; $gt; &quot; &apos;
     * @param String, a string to convert
     * @return String, a converted string
     */
    public static String xmlEsc(String str) {

        // test if str contains chars that has to be escaped
        // most strings do not need escape at all, and
        // for such strings this check eliminates
        // creating new string object
        int len = str.length();
        String esc = "'<>\"&";
        boolean needEscape = false;
        for (int i = 0; i < len; i++) {
            if (esc.indexOf(str.charAt(i)) != -1) {
                needEscape = true;
                break;
            }
        }
        if (!needEscape)
            return str;
        else // escape it
        {
            StringBuffer ret = new StringBuffer();
            for (int i = 0; i < len; i++) {
                char c = str.charAt(i);
                switch (c) {
                case '&':
                    ret.append("&amp;");
                    break;
                case '>':
                    ret.append("&gt;");
                    break;
                case '<':
                    ret.append("&lt;");
                    break;
                case '"':
                    ret.append("&quot;");
                    break;
                case '\'':
                    ret.append("&apos;");
                    break;
                default:
                    ret.append(c);
                    break;
                }
            }
            return ret.toString();
        }
    }
}

Related Tutorials