diff --git a/src/main/org/apache/tools/ant/util/DOMElementWriter.java b/src/main/org/apache/tools/ant/util/DOMElementWriter.java index 8f4939b..578e2f2 100644 --- a/src/main/org/apache/tools/ant/util/DOMElementWriter.java +++ b/src/main/org/apache/tools/ant/util/DOMElementWriter.java @@ -21,6 +21,7 @@ package org.apache.tools.ant.util; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; @@ -233,7 +234,7 @@ public class DOMElementWriter { case Node.CDATA_SECTION_NODE: out.write(""); break; @@ -484,21 +485,60 @@ public class DOMElementWriter { * http://www.w3.org/TR/1998/REC-xml-19980210#charsets and * 2.7 http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect.

+ * @param out where to send the output. * @param value the value to be encoded. * @return the encoded value. - */ - public String encodedata(final String value) { + public void encodedata(Writer out, String value) throws IOException { final int len = value.length(); - StringBuffer sb = new StringBuffer(len); - for (int i = 0; i < len; ++i) { - final char c = value.charAt(i); - if (isLegalCharacter(c)) { - sb.append(c); + 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; } } + } - return StringUtils.replace(sb.substring(0), "]]>", "]]]]>"); + /** + * Drop characters that are illegal in XML documents. + * + *

Also ensure that we are not including an ]]> + * marker by replacing that sequence with + * &#x5d;&#x5d;&gt;.

+ * + *

See XML 1.0 2.2 + * http://www.w3.org/TR/1998/REC-xml-19980210#charsets and + * 2.7 http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect.

+ * @param value the value to be encoded. + * @return the encoded value. + */ + public String encodedata(String value) { + final StringWriter out = new StringWriter(); + try { + encodedata(out, value); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + return out.toString(); } /**