Java tutorial
//package com.java2s; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** * Sets element CDATA data * * @param e * the lement * @param data * the new data */ public static void setElementCDataValue(Element e, String data) { CDATASection txt = getElementCDataNode(e); if (txt != null) { txt.setData(data); } else { txt = e.getOwnerDocument().createCDATASection(data); e.appendChild(txt); } } /** * Returns element's CDATA Node * * @param element * the element which CDATA node is returned * @return CDATA node */ public static CDATASection getElementCDataNode(Element element) { return (CDATASection) getChildNodeByType(element, Node.CDATA_SECTION_NODE); } private static Node getChildNodeByType(Element element, short nodeType) { if (element == null) { return null; } NodeList nodes = element.getChildNodes(); if (nodes == null || nodes.getLength() < 1) { return null; } Node node; String data; for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); short type = node.getNodeType(); if (type == nodeType) { if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { data = ((Text) node).getData(); if (data == null || data.trim().length() < 1) { continue; } } return node; } } return null; } }