Java XML Element Get Value getTextContent(Element element)

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

Description

Obtain the text content of an element.

License

Open Source License

Parameter

Parameter Description
element The element whose text content is desired.

Return

If the element has no text or CDATA children, the value is an empty string. Otherwise, the value is the string representation of all the text and CDATA children, with leading and trailing whitespace removed.

Declaration

public static String getTextContent(Element element) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Element;

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

public class Main {
    /**/*from ww  w. j  a v  a 2s.c  o  m*/
    Obtain the text content of an element.  
        
    @param element
    The element whose text content is desired.
    @return
    If the element has no text or CDATA children, the value is
    an empty string.  Otherwise, the value is the string
    representation of all the text and CDATA children, with
    leading and trailing whitespace removed. 
    **/
    public static String getTextContent(Element element) {
        return getTextContent(element, true);
    }

    /**
    Obtain the text content of an element.  
        
    @param element
    The element whose text content is desired.
    @param trim
    Whether leading and trailing whitespace should be removed.
    @return
    If the element has no text or CDATA children, the value is
    an empty string.  Otherwise, the value is the string
    representation of all the text and CDATA children.
    **/
    public static String getTextContent(Element element, boolean trim) {
        String result = null;

        NodeList nodes = element.getChildNodes();
        if (nodes.getLength() == 0) {
            result = "";
        } else {
            StringBuffer buf = new StringBuffer(64);
            Node node;

            int nNodes = nodes.getLength();
            int i = -1;
            while (++i < nNodes) {
                node = nodes.item(i);
                short nodeType = node.getNodeType();
                if (nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE) {
                    String text = node.getNodeValue();
                    buf.append(text);
                }
            }
            result = buf.toString();
            if (trim) {
                result = result.trim();
            }
        }

        return result;
    }
}

Related

  1. getTextContent(Element element)
  2. getTextContent(Element element)
  3. getTextContent(Element element)
  4. getTextContent(Element element)
  5. getTextContent(Element element)
  6. getTextContentFromFirstElementByTagName(Element element, String tagName)
  7. getTextContentOfElement(Element elem, String tagName, boolean required)
  8. getTextContentOfElements(Element elem, String tagName)
  9. getTextContents(Element e)