Java String escape for XML
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String s = "&&demo2s.com'''&&&"; System.out.println(xmlEscape(s)); }/*from ww w . j a v a 2 s .c om*/ /** * Returns a form of "s" appropriate for including in an XML document, after * escaping certain special characters (e.g. '&' => '&', etc.) */ public static String xmlEscape(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("""); break; case '&': sb.append("&"); break; case '\'': sb.append("'"); break; case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '\n': sb.append("
"); break; case '\r': sb.append("
"); break; case '\t': sb.append("	"); break; case '\0': // \0 is not a valid XML char - skip it break; default: sb.append(ch); break; } } return sb.toString(); } }