Java XML CDATA Add addCDATAElement(Node parent, String name, String data, Attr[] attrs)

Here you can find the source of addCDATAElement(Node parent, String name, String data, Attr[] attrs)

Description

Add a CDATA element with attributes.

License

LGPL

Parameter

Parameter Description
parent parent node
name node name
data node data
attrs attributes

Declaration

public static Element addCDATAElement(Node parent, String name, String data, Attr[] attrs) 

Method Source Code

//package com.java2s;
/*//from w  w  w .j a  va 2s. co m
 * JFox - The most lightweight Java EE Application Server!
 * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
 *
 * JFox is licenced and re-distributable under GNU LGPL.
 */

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**
     * Add a CDATA element.
     *
     * @param parent parent node
     * @param name   node name
     * @param data   node data
     */
    public static Element addCDATAElement(Node parent, String name, String data) {
        return addCDATAElement(parent, name, data, null);
    }

    /**
     * Add a CDATA element with attributes.
     * <p/>
     * NOTE: Serializing a XML document via TRAX changes "\r\n" to "\r\r\n" in
     * a CDATA section. Serializing with the Xalan XMLSerializer works fine.
     *
     * @param parent parent node
     * @param name   node name
     * @param data   node data
     * @param attrs  attributes
     */
    public static Element addCDATAElement(Node parent, String name, String data, Attr[] attrs) {
        Element element;
        CDATASection cdata;
        if (parent instanceof Document) {
            element = ((Document) parent).createElement(name);
            /*
            * Creates a <code>CDATASection</code> node whose value is the
            * specified.
            */
            cdata = ((Document) parent).createCDATASection(data);
        } else {
            element = parent.getOwnerDocument().createElement(name);
            cdata = parent.getOwnerDocument().createCDATASection(data);
        }

        if (attrs != null && attrs.length > 0) {
            for (Attr attr : attrs) {
                element.setAttributeNode(attr);
            }
        }

        element.appendChild(cdata);
        parent.appendChild(element);
        return element;
    }
}

Related

  1. addCDATA(final String xML)
  2. addCData(String xml)
  3. addCdataNode(Element element, String tagName, String value)
  4. addCDATAstring(String value)
  5. addChildCdataElement(Node parent, String name, String cdata)
  6. addNodeCDATAValue(Node node, String name, String value)