Java tutorial
//package com.java2s; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main { /** * Adds a new element containing a CDATA section to the parent element * @param parent the parent element to add the new element to * @param namespaceURI the namespace of the added element's tag name, or null if there isn't any.. * @param tag the tag name of the new element * @param text the text of the CDATA section (if text is null or empty no CDATA section will be added). */ public static void addTextElementNS(Element parent, String namespaceURI, String tag, String text) { // Add an element with the given tag name. Document document = parent.getOwnerDocument(); Element textElement = namespaceURI != null ? document.createElementNS(namespaceURI, tag) : document.createElement(tag); parent.appendChild(textElement); if (text != null && text.length() > 0) { CDATASection cdata = createCDATASection(document, text); textElement.appendChild(cdata); } } /** * Creates a <code>CDATASection</code> node whose value is the specified string. This is different from * Document.createCDATASection() in that this method first converts all "\r\n" and "\r" to "\n" to guard * against XML "features" that transform "\r\n" to "\r\r\n" on output. * @param document * @param data The data for the <code>CDATASection</code> contents. * @return The new <code>CDATASection</code> object. * @exception org.w3c.dom.DOMException * NOT_SUPPORTED_ERR: Raised if this document is an HTML document. */ public static CDATASection createCDATASection(Document document, String data) { String convertedData = convertNewLines(data); return document.createCDATASection(convertedData); } /** * Convert instances of a newline in a string to '\n'. * This is particularly necessary when creating a CDATA node from Windows, as the newline separator on this * platform is "\r\n", which (unbelievably) is serialized to "\r\r\n" as a "feature"! Of course, when this is * read back in, it is converted to "\n\n", meaning that the text was converted from single to double spaced. * To guard against this, all instances of "\r\n" and "\r" are converted to "\n". * @param stringToConvert the string to convert. * @return the converted string. */ private static String convertNewLines(String stringToConvert) { return stringToConvert.replaceAll("\r\n", "\n").replaceAll("\r", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } }