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) { String entity = "&#" + (str[i] & 0xFF) + ";"; 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) { ret += "&#" + (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; } }