Java tutorial
//package com.java2s; //License from project: Apache License public class Main { /** * Escape XML characters. * Suggested by hussein_shafie * @param s value needed to be escaped * @return escaped value */ public static String escapeXML(final String s) { final char[] chars = s.toCharArray(); return escapeXML(chars, 0, chars.length); } /** * Escape XML characters. * Suggested by hussein_shafie * @param chars char arrays * @param offset start position * @param length arrays lenth * @return escaped value */ public static String escapeXML(final char[] chars, final int offset, final int length) { final StringBuilder escaped = new StringBuilder(); final int end = offset + length; for (int i = offset; i < end; ++i) { final char c = chars[i]; switch (c) { case '\'': escaped.append("'"); break; case '\"': escaped.append("""); break; case '<': escaped.append("<"); break; case '>': escaped.append(">"); break; case '&': escaped.append("&"); break; default: escaped.append(c); } } return escaped.toString(); } }