import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CDataBug { public static void main(String[] args) throws Exception { try (StringWriter out = new StringWriter()) { output(createDocument(), out); dump(out.toString()); } } private static Document createDocument() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); // CData section with windows line separators Element windows = document.createElement("windows"); windows.appendChild(document.createCDATASection("one\r\ntwo\r\nthree")); // CData section with unix line separators Element unix = document.createElement("unix"); unix.appendChild(document.createCDATASection("one\ntwo\nthree")); Element newlines = document.createElement("newlines"); newlines.appendChild(unix); newlines.appendChild(windows); document.appendChild(newlines); return document; } private static void dump(String text) { boolean showNewlines = false; for (int i = 0, size = text.length(); i < size; i++) { char c = text.charAt(i); switch (c) { case '[' : { showNewlines = true; System.out.print(c); break; } case ']' : { showNewlines = false; System.out.print(c); break; } case '\r' : { if (showNewlines) { System.out.print(""); continue; } } case '\n' : { if (showNewlines) { System.out.print(""); } } default : { System.out.print(c); } } } } private static void output(Document document, StringWriter out) throws Exception { Transformer output = TransformerFactory.newInstance().newTransformer(); output.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); output.setOutputProperty(OutputKeys.INDENT, "yes"); output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1"); output.transform(new DOMSource(document), new StreamResult(out)); } }