Java examples for XML:XML String Escape
escapes & characters to & only
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String str = "java2s.com"; System.out.println(xmlAmp(str)); }/*from w ww . j a v a 2 s . c o m*/ /** * escapes & characters to & only * @param String, a string to convert * @return String, a converted string */ public static String xmlAmp(String str) { int index = 0; int strIndex = 0; int semiIndex = 0; StringBuffer ret = new StringBuffer(); index = str.indexOf("&", strIndex); while (index > -1) { ret.append(str.substring(strIndex, index)); semiIndex = str.indexOf(";", index); if (semiIndex > -1) { if ((semiIndex - index) > 7 && !isInComment(str, index)) { ret.append("&"); } else { ret.append("&"); } } strIndex = index + 1; index = str.indexOf("&", strIndex); } ret.append(str.substring(strIndex)); return (ret.toString()); } /** * analysis the position of character is in the comment section * @param String, whole text paragraph * @param int, the character index position within text * @return booelan, true means position in comment section */ public static boolean isInComment(String str, int index) { int strComment = 0; int endComment = 0; boolean ret = false; strComment = str.lastIndexOf("<!--", index); if (strComment > -1) { endComment = str.lastIndexOf("-->", index); if (endComment < strComment) { ret = true; } } return (ret); } }