Simple DOM elements finder. - Java XML

Java examples for XML:DOM Element

Description

Simple DOM elements finder.

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 ww w.j a v  a  2  s.  com
     * Simple DOM elements finder.
     *
     * @param fromnode node from when we start deep search
     * @param name the node name to search
     * @return the list of elements matching the seeken name
     */
    protected static List<Element> findElements(Node fromnode, String name) {
        NodeList nodelist = fromnode.getChildNodes();
        List<Element> list = new ArrayList<Element>();
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (name.equals(node.getNodeName())) {
                    list.add((Element) node);
                }
                list.addAll(findElements(node, name));
            }
        }
        return list;
    }
}

Related Tutorials