Java XML Element Text getElementText(final Element element)

Here you can find the source of getElementText(final Element element)

Description

Returns the text within a specified element.

License

Open Source License

Parameter

Parameter Description
element Element whose text should be returned.

Return

Element's text.

Declaration

public static String getElementText(final Element element) 

Method Source Code

//package com.java2s;

import org.w3c.dom.CDATASection;

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

public class Main {
    /**/* w  ww  .j a  v  a 2s  .c  om*/
     * Returns the text within a specified element. Can be optimized for elements with a single text node (common case).
     * 
     * @param element
     *            Element whose text should be returned.
     * @return Element's text.
     */
    public static String getElementText(final Element element) {
        final StringBuffer elementText = new StringBuffer(256);

        for (Node childNode = element.getFirstChild(); childNode != null; childNode = childNode
                .getNextSibling()) {
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                final Text textNode = (Text) childNode;

                elementText.append(textNode.getData());
            } else if (childNode.getNodeType() == Node.CDATA_SECTION_NODE) {
                final CDATASection cdataNode = (CDATASection) childNode;

                elementText.append(cdataNode.getData());
            }
        }

        return elementText.toString().trim();
    }
}

Related

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