Get all of the XML element nodes from a NodeList - Java XML

Java examples for XML:XML Node

Description

Get all of the XML element nodes from a NodeList

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 {
    /**/*from   w  w w . j a  v  a  2 s .c  om*/
     * Get all of the element nodes from a NodeList
     * 
     * @param nodeList
     *          The NodeList to pull the Elements from
     * 
     * @return
     *          A List containing all of the Element objects
     *          that were contained in the NodeList.  If there
     *          were no Elements and empty List will be returned.
     */
    public static List<Element> getElementList(NodeList nodeList) {

        List<Element> elements = new ArrayList<Element>();

        if (!(nodeList == null) && nodeList.getLength() > 0) {

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                // Check if the node is an element and add it to the list
                if (Node.ELEMENT_NODE == node.getNodeType()) {
                    elements.add((Element) node);
                }
            }
        }

        return elements;
    }
}

Related Tutorials