get XML Children Element and return a List of Element - Java XML

Java examples for XML:XML Element Child

Description

get XML Children Element and return a List of Element

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    public static List<Element> getChildren(Element element, String tagName) {
        List<Element> children = new ArrayList<>();
        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                Element child = (Element) node;
                if (tagName != null && child.getTagName().equals(tagName))
                    children.add(child);
            }//from w  w  w . ja v  a  2s. c  om
        }
        return children;
    }
}

Related Tutorials