Get the first child XML element with the specified name from the given parent node. - Java XML

Java examples for XML:XML Node Child

Description

Get the first child XML element with the specified name from the given parent node.

Demo Code

/*/*from   w w w .j av a2 s . com*/
   Copyright (C) 2016 HermeneutiX.org

   This file is part of SciToS.

   SciToS is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   SciToS is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with SciToS. If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

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

public class Main {
    /**
     * Get the first child element with the specified name from the given parent node. Returns {@code null} if no child element with the specified
     * name exists.
     *
     * @param parentNode
     *            node to retrieve a single child element from
     * @param childNodeName
     *            name of the targeted child element
     * @return the first child element with the given name
     */
    public static Element getChildElement(final Node parentNode,
            final String childNodeName) {
        final NodeList candidates = parentNode.getChildNodes();
        final int childCount = candidates.getLength();
        for (int childIndex = 0; childIndex < childCount; childIndex++) {
            final Node singleChild = candidates.item(childIndex);
            if (singleChild instanceof Element
                    && childNodeName.equals(((Element) singleChild)
                            .getTagName())) {
                // found a matching child element, ignore potentially following matches
                return (Element) singleChild;
            }
        }
        return null;
    }
}

Related Tutorials