Returns the first child element retrieved by tag name from the parent node and null otherwise. - Java XML

Java examples for XML:XML Element Child

Description

Returns the first child element retrieved by tag name from the parent node and null otherwise.

Demo Code

/**/*from   w w  w .j av a2 s .  c o m*/
 *  Copyright (c) 2013-2014 Angelo ZERR.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *  Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
 */
//package com.java2s;

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

public class Main {
    /**
     * Returns the first child element retrieved by tag name from the parent
     * node and null otherwise.
     * 
     * @param parentNode
     *            parent node.
     * @param elementName
     *            element name to found.
     * @return the first child element
     */
    public static Element getFirstChildElementByTagName(Node parentNode,
            String elementName) {
        Element result = null;

        if (parentNode.getNodeType() == Node.DOCUMENT_NODE) {
            result = ((Document) parentNode).getDocumentElement();
            if (!result.getNodeName().equals(elementName)) {
                result = null;
            }
        } else {
            NodeList nodes = parentNode.getChildNodes();
            Node node;
            for (int i = 0; i < nodes.getLength(); i++) {
                node = nodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE
                        && node.getNodeName().equals(elementName)) {
                    result = (Element) node;
                    break;
                }
            }
        }
        return result;
    }
}

Related Tutorials