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