Get all child XML elements with the specified name(s) from the given parent node. - Java XML

Java examples for XML:XML Node Child

Description

Get all child XML elements with the specified name(s) from the given parent node.

Demo Code

/*/*from  ww  w.jav a 2  s.  c  o m*/
   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 java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

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

public class Main {
    /**
     * Get all child elements with the specified name(s) from the given parent node. Returns an empty list if no child element with the specified
     * name(s) exist.
     *
     * @param parentNode
     *            node to retrieve the child elements from
     * @param childNodeNames
     *            names of the targeted child elements
     * @return all child elements with the given name
     */
    public static List<Element> getChildElements(final Node parentNode,
            final String... childNodeNames) {
        final List<Element> children = new LinkedList<Element>();
        final NodeList candidates = parentNode.getChildNodes();
        final int childCount = candidates.getLength();
        final List<String> targetNodeNames = Arrays.asList(childNodeNames);
        for (int childIndex = 0; childIndex < childCount; childIndex++) {
            final Node singleChild = candidates.item(childIndex);
            if (singleChild instanceof Element
                    && (targetNodeNames.isEmpty() || targetNodeNames
                            .contains(((Element) singleChild).getTagName()))) {
                children.add((Element) singleChild);
            }
        }
        return children;
    }
}

Related Tutorials