get XML Child Elements - Java XML

Java examples for XML:XML Element Child

Description

get XML Child Elements

Demo Code


//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

public class Main {
    /**//from  ww w.  j  ava2s.c  o m
     * 
     * @param parent
     * @param childName
     * @return
     */
    public static List getChildElements(Element parent, String childName) {
        NodeList children = parent.getChildNodes();
        List list = new ArrayList();
        int size = children.getLength();

        for (int i = 0; i < size; i++) {
            Node node = children.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;

                if (childName.equals(element.getNodeName())) {
                    list.add(element);
                }
            }
        }

        return list;
    }
}

Related Tutorials