Java tutorial
//package com.java2s; /* * Copyright (c) Mirth Corporation. All rights reserved. * http://www.mirthcorp.com * * The software in this package is published under the terms of the MPL * license a copy of which has been included with this distribution in * the LICENSE.txt file. */ public class Main { private static final String[] encoderXml = new String[0x100]; public static String encode(char s) { StringBuffer buffer = new StringBuffer(4); char c = s; int j = c; if (j < 0x100 && encoderXml[j] != null) { buffer.append(encoderXml[j]); // have a named encoding buffer.append(';'); } else if (j < 0x80) { buffer.append(c); // use ASCII value } else { buffer.append("&#"); // use numeric encoding buffer.append((int) c); buffer.append(';'); } return buffer.toString(); } public static String encode(String s) { int length = s.length(); StringBuffer buffer = new StringBuffer(length * 2); for (int i = 0; i < length; i++) { char c = s.charAt(i); buffer.append(encode(c)); } return buffer.toString(); } public static String encode(char[] text, int start, int length) { StringBuffer buffer = new StringBuffer(length * 2); for (int i = start; i < length + start; i++) { char c = text[i]; int j = c; if (j < 0x100 && encoderXml[j] != null) { buffer.append(encoderXml[j]); // have a named encoding buffer.append(';'); } else if (j < 0x80) { buffer.append(c); // use ASCII value } else { buffer.append("&#"); // use numeric encoding buffer.append((int) c); buffer.append(';'); } } return buffer.toString(); } }