Java XML Element Text getElementTextValue(Element element)

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

Description

Get the element text value.

License

Apache License

Parameter

Parameter Description
element The element to get the name for

Return

The text value

Declaration

public static String getElementTextValue(Element element) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**//from  ww w  . ja  v a  2s  . c o m
     * Get the element text value.  Locate the text node and return
     * its contents.
     *
     * @param element The element to get the name for
     * @return The text value
     */
    public static String getElementTextValue(Element element) {
        String value = "";

        // get the text node
        Node node = getElementTextNode(element);
        if (node != null) {
            value = node.getNodeValue();
        }

        // if the entire string is whitespace ignore this
        // but don't trim the whitespace if it is there
        String testValue = value.trim();
        if (testValue.length() <= 0) {
            value = "";
        }
        return (value);
    }

    /**
     * Get the element text node.  Locate the text node and return it.  For example;
     * <element>this is the text node</element>
     *
     * @param element The element to get the text node for
     * @return The text node
     */
    public static Node getElementTextNode(Element element) {

        Node textNode = null;

        // go through each child element
        Node node;
        short nodeType;
        NodeList children = element.getChildNodes();
        for (int ii = 0; ii < children.getLength(); ii++) {
            node = children.item(ii);
            nodeType = node.getNodeType();
            if (nodeType == Node.TEXT_NODE) {
                textNode = node;
                break;
            } else if (nodeType == Node.CDATA_SECTION_NODE) {
                textNode = node;
                break;
            }
        }
        return (textNode);
    }
}

Related

  1. getElementText(Element root, String tagname)
  2. getElementText(final Element element)
  3. getElementTextByTagName(Element n, String elementName)
  4. getElementTextDataNoEx(Element element, boolean unindent)
  5. getElementTextOrNull(final XMLStreamReader reader)
  6. getElementTextValue(Element in)
  7. getSimpleElementText(Element element)
  8. getSimpleElementText(Element node)
  9. getSimpleElementText(Element node)