Returns a string representing the plain text content of an element. - Java XML

Java examples for XML:DOM Node Value

Description

Returns a string representing the plain text content of an element.

Demo Code


//package com.java2s;
import org.w3c.dom.*;

public class Main {
    /**//  ww w. ja  va  2s .c o m
     * Returns a string representing the plain text content of an element.
     * Any comments, attributes, elements or other non-text children 
     * are ignored, and all CDATA and Text nodes are merged to 
     * give a single string.
     * 
     * @param   el  the element whose text content is wanted
     * @return  the pure text content.  If there is none, an empty 
     *          string is returned.
     */
    public static String getTextContent(Element el) {
        StringBuffer sb = new StringBuffer();
        for (Node child = el.getFirstChild(); child != null; child = child
                .getNextSibling()) {
            if (child instanceof Text) {
                Text childText = (Text) child;
                sb.append(childText.getData());
            }
        }
        return sb.toString();
    }
}

Related Tutorials