Returns list of 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 list of the first child element retrieved by tag name from the parent node and null otherwise.

Demo Code

/**/* w  w  w . j  a va  2 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 java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

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

public class Main {
    /**
     * Returns list of 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 list of the first child element
     */
    public static Collection<Element> getFirstChildElementsByTagName(
            Node contextNode, String elementName) {
        Collection<Element> elements = null;
        Element result = null;

        if (contextNode.getNodeType() == Node.DOCUMENT_NODE) {
            result = ((Document) contextNode).getDocumentElement();
            if (!result.getNodeName().equals(elementName)) {
                result = null;
            }
        } else {
            NodeList nodes = contextNode.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)) {
                    if (elements == null) {
                        elements = new ArrayList<Element>();
                    }
                    result = (Element) node;
                    elements.add(result);
                }
            }
        }
        if (elements == null) {
            return Collections.emptyList();
        }
        return elements;
    }
}

Related Tutorials