Java tutorial
//package com.java2s; /* Copyright 2013, 2016 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Main { /** * Translates special characters to xml equivalents * like <b>></b> and <b>&</b>. Please note that non valid xml chars * are not changed, hence you might want to use * replaceNonValidXmlCharacters() or stripNonValidXmlCharacters() too. */ public static String encodeChars(String string) { if (string == null) { return null; } int length = string.length(); char[] characters = new char[length]; string.getChars(0, length, characters, 0); return encodeChars(characters, 0, length); } /** * Translates special characters to xml equivalents * like <b>></b> and <b>&</b>. Please note that non valid xml chars * are not changed, hence you might want to use * replaceNonValidXmlCharacters() or stripNonValidXmlCharacters() too. */ public static String encodeChars(char[] chars, int offset, int length) { if (length <= 0) { return ""; } StringBuilder encoded = new StringBuilder(length); String escape; for (int i = 0; i < length; i++) { char c = chars[offset + i]; escape = escapeChar(c); if (escape == null) encoded.append(c); else encoded.append(escape); } return encoded.toString(); } /** * Conversion of special xml signs. Please note that non valid xml chars * are not changed, hence you might want to use * replaceNonValidXmlCharacters() or stripNonValidXmlCharacters() too. **/ private static String escapeChar(char c) { switch (c) { case ('<'): return "<"; case ('>'): return ">"; case ('&'): return "&"; case ('\"'): return """; case ('\''): // return "'"; // apos does not work in Internet Explorer return "'"; } return null; } }