Java examples for XML:XML String Escape
escapes & < > " ' characters to & < $gt; " '
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String str = "java2s.com"; System.out.println(xmlEsc(str)); }/* w ww.ja v a 2 s . c om*/ /** * escapes & < > " ' characters to & < $gt; " ' * @param String, a string to convert * @return String, a converted string */ public static String xmlEsc(String str) { // test if str contains chars that has to be escaped // most strings do not need escape at all, and // for such strings this check eliminates // creating new string object int len = str.length(); String esc = "'<>\"&"; boolean needEscape = false; for (int i = 0; i < len; i++) { if (esc.indexOf(str.charAt(i)) != -1) { needEscape = true; break; } } if (!needEscape) return str; else // escape it { StringBuffer ret = new StringBuffer(); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '&': ret.append("&"); break; case '>': ret.append(">"); break; case '<': ret.append("<"); break; case '"': ret.append("""); break; case '\'': ret.append("'"); break; default: ret.append(c); break; } } return ret.toString(); } } }