Java XML Node Value setText(Element parentNode, String data)

Here you can find the source of setText(Element parentNode, String data)

Description

Sets data to be the TEXT content of element

License

LGPL

Parameter

Parameter Description
parentNode the parent element.
data the data to set.

Declaration

public static void setText(Element parentNode, String data) 

Method Source Code

//package com.java2s;
/*//from ww  w .j a v  a 2  s.  co  m
 * Jitsi, 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 {
    /**
     * Sets data to be the TEXT content of element
     *
     * @param parentNode the parent element.
     * @param data the data to set.
     */
    public static void setText(Element parentNode, String data) {
        if (data == null)
            return;

        Text txt = getTextNode(parentNode);

        if (txt != null)
            txt.setData(data);
        else {
            txt = parentNode.getOwnerDocument().createTextNode(data);
            parentNode.appendChild(txt);
        }
    }

    /**
     * Returns element's TEXT child node (if it has one).
     * @param element the element whose TEXT we need to get.
     * @return a <tt>Text</tt> object containing the specified element's
     * text content.
     */
    public static Text getTextNode(Element element) {
        return (Text) getChildByType(element, Node.TEXT_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. getValueOfValueNode(Node n)
  2. getValues(Node metric)
  3. nodeToDouble(Node node)
  4. putAll(final NamedNodeMap dst, final NamedNodeMap src)
  5. setText(Element parent, String text)
  6. setText(Node n, String text)
  7. setText(Node node, String text)
  8. setText(Node node, String text)
  9. setText(Node node, String text)