Java XML Element Get getElementContent(final Element element)

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

Description

Get the content of the given element.

License

LGPL

Parameter

Parameter Description
element The element to get the content for.

Return

The content of the element or null.

Declaration

public static String getElementContent(final Element element) throws Exception 

Method Source Code

//package com.java2s;
/*//from   ww w  .  j  a  va2s  . co m
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */

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

public class Main {
    /**
     * Get the content of the given element.
     *
     * @param element The element to get the content for.
     * @return The content of the element or null.
     */
    public static String getElementContent(final Element element) throws Exception {
        return getElementContent(element, null);
    }

    /**
     * Get the content of the given element.
     *
     * @param element   The element to get the content for.
     * @param defaultStr The default to return when there is no content.
     * @return The content of the element or the default.
     */
    public static String getElementContent(Element element, String defaultStr) throws Exception {
        if (element == null) {
            return defaultStr;
        }

        final NodeList children = element.getChildNodes();
        final StringBuilder result = new StringBuilder("");
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() == Node.TEXT_NODE
                    || children.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                result.append(children.item(i).getNodeValue());
            }
            //         else if ( children.item( i ).getNodeType() == Node.COMMENT_NODE ) {
            //            // Ignore comment nodes
            //         }
        }
        return result.toString().trim();
    }
}

Related

  1. getElementContent(Element elem)
  2. getElementContent(Element elem)
  3. getElementContent(Element element, String defaultStr)
  4. getElementContent(Element element, String defaultStr)
  5. getElementContent(final Element el)
  6. getElementContent(final Element element, final boolean trim)
  7. getElementContents(Element element, String elementName)
  8. getElementDescendant(Element elem, String ns_uri, String tagName)
  9. getElementForLine(Document document, int line)