Returns the text-content of the first XML element in a document with a given tag name. - Java XML

Java examples for XML:DOM Document

Description

Returns the text-content of the first XML element in a document with a given tag name.

Demo Code


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

public class Main {
    /**//ww w . ja  v  a  2 s  .c  o m
     * Returns the text-content of the first element in a document with a given tag name.
     * This is useful for well structured documents when it is known that there is only
     * one such element.
     * 
     * @param document The document to search within.
     * @param tagname The name of the element to retrieve.
     * @return The text content of the element. Text nodes therein are appended for the result, but
     * no further descendants are included. If the element could not be found, the empty string is
     * returned.
     */
    public static String getNodeContent(Document document, String tagname) {
        NodeList list = document.getElementsByTagName(tagname);
        if (list.getLength() < 1) {
            //            log.debug("Not found: " + tagname);
            return "";
        }
        Element tag = (Element) list.item(0);
        NodeList content = tag.getChildNodes();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < content.getLength(); i++) {
            Node node = content.item(i);
            if (node instanceof Text) {
                buf.append(((Text) node).getNodeValue());
            }
        }
        String textcontent = buf.toString().trim();
        //        log.debug("getNodeContent: " + tagname + " = [" + textcontent + "]");
        return textcontent;
    }
}

Related Tutorials