Java tutorial
//package com.java2s; public class Main { public static Object escapeXml(Object obj) { if (obj == null) { return null; } else if (obj instanceof CharSequence) { return escapeXml((CharSequence) obj); } else { return obj; } } public static String escapeXml(CharSequence str) { if (str == null) { return null; } StringBuilder res = null; int strLength = str.length(); for (int i = 0; i < strLength; i++) { char c = str.charAt(i); String repl = encodeXMLChar(c); if (repl == null) { if (res != null) { res.append(c); } } else { if (res == null) { res = new StringBuilder(str.length() + 5); for (int k = 0; k < i; k++) { res.append(str.charAt(k)); } } res.append(repl); } } return res == null ? str.toString() : res.toString(); } /** * Encodes a char to XML-valid form replacing &,',",<,> with special XML encoding. * * @param ch char to convert * @return XML-encoded text */ public static String encodeXMLChar(char ch) { switch (ch) { case '&': return "&"; case '\"': return """; case '\'': return "'"; case '<': return "<"; case '>': return ">"; default: return null; } } }