Java tutorial
//package com.java2s; import java.util.*; public class Main { public final static String XML_ESCAPE_DELIMITERS = "&'<>\""; /** * Replace all occurrences of the characters &, ', ", < and > by the escaped * characters &, ", ', < and > */ public static String XMLEscape(String s) { if (s == null) { return ""; } boolean contains = false; for (int i = 0; i < XML_ESCAPE_DELIMITERS.length(); i++) { if (s.indexOf(XML_ESCAPE_DELIMITERS.charAt(i)) != -1) { contains = true; } } if (!contains) { return s; } if (s.length() == 0) { return s; } StringTokenizer tokenizer = new StringTokenizer(s, XML_ESCAPE_DELIMITERS, true); StringBuffer result = new StringBuffer(); while (tokenizer.hasMoreElements()) { String substring = tokenizer.nextToken(); if (substring.length() == 1) { switch (substring.charAt(0)) { case '&': result.append("&"); break; //case '\'' : // result.append("'"); // break; case ';': result.append("\\;"); break; case '<': result.append("<"); break; case '>': result.append(">"); break; case '\"': result.append("""); break; // case '\n' : // result.append("\\n"); // break; default: result.append(substring); } } else { result.append(substring); } } return result.toString(); } }