get Simple Element Text that takes the name of XML element to get the text from. - Java XML

Java examples for XML:DOM Element

Description

get Simple Element Text that takes the name of XML element to get the text from.

Demo Code

/*//from   w w w  . j a va  2s  .  c  om
 * DOMUtil.java
 * Copyright (C) 2006 Nicholas Killewald
 * Portions Copyright (C) 2005 Patrick Niemeyer
 *
 * This file is distributed under the terms of the BSD license.
 * See the LICENSE file under the toplevel images/ directory for terms.
 */
//package com.java2s;
import org.w3c.dom.Element;

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

public class Main {
    /**
     * Specialized form of getSimpleElementText that takes the name of an
     * element to get the text from.  Note that this will only take the first
     * occurrence of the named element.
     *
     * @param node element to retrieve the text from
     * @param name named element as a child of <code>node</code> to retrieve the text from
     * @return the text in the named element
     * @see #getSimpleElementText(Element)
     */
    public static String getSimpleElementText(Element node, String name) {
        Element namedElement = getFirstElement(node, name);
        return getSimpleElementText(namedElement);
    }

    /**
     * Returns the text contained in a simple node.  A "simple node", in this
     * case, means only the text elements with no extra tags in between.  Any
     * tags like that will be ignored.  You'll need to navigate the tree
     * yourself to dig anything else out of it.
     *
     * @param node element to retrieve text from
     * @return the text in the element
     */
    public static String getSimpleElementText(Element node) {
        StringBuffer sb = new StringBuffer();
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child instanceof Text)
                sb.append(child.getNodeValue());
        }
        return sb.toString();
    }

    /**
     * Get the first element with the given name as a child of the given
     * element.  A RuntimeException will be thrown if the named element doesn't
     * exist.
     *
     * @param element element to get a child from
     * @param name name of child
     * @return the element in question
     */
    public static Element getFirstElement(Element element, String name) {
        NodeList nl = element.getElementsByTagName(name);
        if (nl.getLength() < 1)
            throw new RuntimeException("Element: " + element
                    + "does not contain: " + name);
        return (Element) nl.item(0);
    }
}

Related Tutorials