Java XML CDATA Get getCDataValue(Node node, String tag)

Here you can find the source of getCDataValue(Node node, String tag)

Description

Returns the CDATA value of the subnode of specified node with the specified tag.

License

Open Source License

Parameter

Parameter Description
node The parent DOM node
tag The tag of the node

Return

the value

Declaration

public static String getCDataValue(Node node, String tag) 

Method Source Code


//package com.java2s;

import org.w3c.dom.*;

public class Main {
    /**/*from  w w  w  .  j a  v a  2 s .  c  om*/
     * Returns the CDATA value of the subnode of specified node with the specified
     * tag. For example: 
     * <pre>
     *     &lt;test&gt;
     *        &lt;host&gt;localhost&lt;host&gt;
     *     &lt;/test&gt;
     * </pre>
     * would return <em>localhost</em>, for node being the <code>test</code>
     * node and tag being <code>host</code>.
     * 
     * @param node The parent DOM node
     * @param tag The tag of the node
     * @return the value
     */
    public static String getCDataValue(Node node, String tag) {
        String ret = null;
        Node child = getChildNode(node, tag);
        if (child != null) {
            NodeList grandchildren = child.getChildNodes();
            Node grandchild = grandchildren.item(0);
            if (grandchild != null) {
                ret = grandchild.getNodeValue();
            }
        }
        return ret;
    }

    /**
     * Return the child node of the specified node with the specified tag.
     *
     * @param node The parent DOM node
     * @param tag The tag of the node
     * @return the child node 
     */
    public static Node getChildNode(Node node, String tag) {
        Node res = null;
        NodeList children = node.getChildNodes();
        int len = (children != null) ? children.getLength() : 0;
        int i = 0;
        while (i < len && res == null) {
            Node child = children.item(i);
            String nodeName = child.getNodeName();
            if (nodeName.equals(tag)) {
                res = child;
            }
            i++;
        }
        return res;
    }
}

Related

  1. getCDATA(Element elem)
  2. getCdata(Element elem)
  3. getCData(Element element)
  4. getCDataNode(Element element)
  5. getChildCdata(Node element, String name)
  6. getChildCharacterData(Element parentEl)
  7. getChildCharacterData(Element parentEl)
  8. getElementCDATAByTagName(Element current, String name, String namespace)