Java XML Element Text getElementText(Element root, String tagname)

Here you can find the source of getElementText(Element root, String tagname)

Description

This methods extracts the text for a named element under the root.

License

Apache License

Parameter

Parameter Description
root The element is contained within this root.
tagname The elemet name to search for

Return

The text under the tag, or null if it is not found or an error occured.

Declaration

public static String getElementText(Element root, String tagname) 

Method Source Code

//package com.java2s;
/**/*from  ww  w. j a  v  a  2  s .c  om*/
 * Copyright 1999-2009 The Pegadi Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.w3c.dom.*;

public class Main {
    /**
     * This methods extracts the text for a named element under the
     * <code>root</code>. For the moment it uses only the first text node,
     * and only the first element of that type.
     *
     * @param root    The element is contained within this root.
     * @param tagname The elemet name to search for
     * @return The text under the tag, or <code>null</code> if it is not found
     *         or an error occured.
     */
    public static String getElementText(Element root, String tagname) {
        NodeList nameList = root.getElementsByTagName(tagname);

        if (nameList.getLength() > 0) {
            Node text = nameList.item(0).getFirstChild();

            // Find the first text node
            while ((text != null) && !(text instanceof Text)) {
                text = text.getNextSibling();
            }

            if (text == null) {
                return null;
            } else {
                try {
                    return text.getNodeValue();
                } catch (DOMException de) {
                    return null;
                }
            }
        } else {
            return null;
        }
    }
}

Related

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