Java tutorial
//package com.java2s; import java.io.PrintWriter; public class Main { public static void writeXML(PrintWriter out, String str) { for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); switch (ch) { case '<': out.write("<"); break; case '>': out.write(">"); break; case '&': out.write("&"); break; case '"': out.write("""); break; case '\'': out.write("'"); break; case '\r': case '\n': out.write(ch); break; default: if ((ch < 32) || (ch > 126)) { out.write("&#x"); out.write(Integer.toString(ch, 16)); out.write(';'); } else { out.write(ch); } break; } } } }