Java tutorial
//package com.java2s; public class Main { /** * Encode a string so that it can be safely used as text in an element * for XML output. * @param text the element text body. * @return a string so that it can be safely used as text in an element * for XML output. */ public static String escape(String text) { final StringBuffer sb = new StringBuffer(); if (text != null) { char c; final int l = text.length(); for (int i = 0; i < l; i++) { c = text.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': // only needed to avoid ]]> sb.append(">"); break; case '&': sb.append("&"); break; default: if (c > Byte.MAX_VALUE) { sb.append("&#x"); sb.append(Integer.toHexString(c)); sb.append(';'); } else { sb.append(c); } } } } return sb.toString(); } }