Java examples for XML:XML String Escape
replace the xml chars: & to & < to < > to > " to " ' to '
//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;</code> * <code><</code> to <code>&lt;</code> * <code>></code> to <code>&gt;</code> * <code>"</code> to <code>&#034;</code> * <code>'</code> to <code>&#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(); } }