Java tutorial
//package com.java2s; //License from project: LGPL public class Main { public static byte[] xmlEncode(byte[] str) { byte[] ret = new byte[0]; for (int i = 0; i < str.length; i++) { if ((str[i] & 0xFF) >= 128 || (str[i] & 0xFF) < 32 || (str[i] & 0xFF) == '\'' || (str[i] & 0xFF) == '<' || (str[i] & 0xFF) == '>' || (str[i] & 0xFF) == '"') { String entity = "&#x" + String.format("%02X", str[i]) + ";"; ret = concat(ret, entity.getBytes()); } else ret = concat(ret, new byte[] { str[i] }); } return ret; } public static String xmlEncode(String str) { String ret = ""; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 128 || c < 32 || c == '\'' || c == '"' || c == '<' || c == '>') { if (c > 0xFF) ret += "&#x" + String.format("%04x", (int) c) + ";"; else ret += "&#x" + String.format("%02x", (int) c) + ";"; } else ret += c; } return ret; } public static byte[] concat(byte[] b1, byte[] b2) { byte[] ret = new byte[b1.length + b2.length]; System.arraycopy(b1, 0, ret, 0, b1.length); System.arraycopy(b2, 0, ret, b1.length, b2.length); return ret; } }