Java XML CDATA Get getCData(Element element)

Here you can find the source of getCData(Element element)

Description

Extract the CDATA content of the specified element.

License

LGPL

Parameter

Parameter Description
element the element whose data we need

Return

a String containing the CDATA value of element.

Declaration

public static String getCData(Element element) 

Method Source Code

//package com.java2s;
/*//from www  . j a  v a 2  s  .  c om
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

import org.w3c.dom.*;

public class Main {
    /**
     * Extract the CDATA content of the specified element.
     * @param element the element whose data we need
     * @return a String containing the CDATA value of element.
     */
    public static String getCData(Element element) {
        CDATASection text = getCDataNode(element);
        if (text != null)
            return text.getData().trim();
        else
            return null;
    }

    /**
     * Returns element's CDATA child node (if it has one).
     * @param element the element whose CDATA we need to get.
     * @return a CDATASection object containing the specified element's CDATA
     * content
     */
    public static CDATASection getCDataNode(Element element) {
        return (CDATASection) getChildByType(element, Node.CDATA_SECTION_NODE);
    }

    /**
     * Returns first of the <tt>element</tt>'s child nodes that is of type
     * <tt>nodeType</tt>.
     * @param element the element whose child we need.
     * @param nodeType the type of the child we need.
     * @return a child of the specified <tt>nodeType</tt> or null if none
     * was found.
     */
    public static Node getChildByType(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;
    }
}

Related

  1. getCDATA(Element elem)
  2. getCdata(Element elem)
  3. getCDataNode(Element element)
  4. getCDataValue(Node node, String tag)
  5. getChildCdata(Node element, String name)
  6. getChildCharacterData(Element parentEl)