replace the xml chars: & to &amp; < to &lt; > to &gt; " to &#034; ' to &#039; - Java XML

Java examples for XML:XML String Escape

Description

replace the xml chars: & to &amp; < to &lt; > to &gt; " to &#034; ' to &#039;

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(replaceXmlChar(str));
    }//from  w  w w .j a v  a  2s .  co m

    /** special char in html, this is the highest(int value is bigger) char **/
    public static final int HIGHEST_SPECIAL = '>' + 1;
    /** store the special html char **/
    public static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL][];

    /**
     * <pre>
     * replace the xml chars:
     * <code>&</code> to <code>&amp;amp;</code>
     * <code><</code> to <code>&amp;lt;</code>
     * <code>></code> to <code>&amp;gt;</code>
     * <code>"</code> to <code>&amp;#034;</code>
     * <code>'</code> to <code>&amp;#039;</code>
     * </pre>

     */
    public static String replaceXmlChar(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(str.length() * 2);
        for (int i = 0, len = str.length(); i < len; i++) {
            char c = str.charAt(i);
            if (c < HIGHEST_SPECIAL) {
                char[] escaped = specialCharactersRepresentation[c];
                if (escaped != null) {
                    sb.append(escaped);
                } else {
                    sb.append(c);
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Related Tutorials