import java.io.IOException; import java.io.StringWriter; import java.io.Writer; public class TestCDATAScanner { public static boolean isLegalCharacter(char c) { return (c != '#'); } public static void encodedata(Writer out, String value) throws IOException { final int len = value.length(); int prevEnd = 0, cdataEndPos = value.indexOf("]]>"); while (prevEnd < len) { final int end = (cdataEndPos < 0 ? len : cdataEndPos); // Write out stretches of legal characters in the range [prevEnd, end). for (int prevLegalCharPos = prevEnd; prevLegalCharPos < end; /*empty*/) { int illegalCharPos; for (illegalCharPos = prevLegalCharPos; true; ++illegalCharPos) { if (illegalCharPos >= end || !isLegalCharacter(value.charAt(illegalCharPos))) { break; } } out.write(value, prevLegalCharPos, illegalCharPos - prevLegalCharPos); prevLegalCharPos = illegalCharPos + 1; } if (cdataEndPos >= 0) { out.write("]]]]>"); prevEnd = cdataEndPos + 3; cdataEndPos = value.indexOf("]]>", prevEnd); } else { prevEnd = end; } } } private static void writeEncodedData(Writer out, String value) throws IOException { final int len = value.length(); char lastCopied = '\0'; boolean encode = false; for (int i = 0; i < len; ++i) { final char c = value.charAt(i); if (lastCopied == ']' && c == ']') { encode = true; } if (isLegalCharacter(c)) { out.write(c); if (encode) { out.write("]]> test #]####### ]]## an##other tes######t #]]>##"; writeEncodedData(out, value); out.write('\n'); encodedata(out, value); System.out.println(out.toString()); } }