Java XML Element Find findNodesByType(Element topElm, int type)

Here you can find the source of findNodesByType(Element topElm, int type)

Description

Finds element in DOM tree

License

Open Source License

Parameter

Parameter Description
topElm Top element
nodeName Node name

Return

returns found node

Declaration

public static List<Node> findNodesByType(Element topElm, int type) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

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

public class Main {
    /**/*w w  w.ja v  a  2s. c o m*/
     * Finds element in DOM tree
     * @param topElm Top element
     * @param nodeName Node name
     * @return returns found node
     */
    public static List<Node> findNodesByType(Element topElm, int type) {
        List<Node> retvals = new ArrayList<Node>();
        if (topElm == null)
            throw new IllegalArgumentException("topElm cannot be null");
        synchronized (topElm.getOwnerDocument()) {
            Stack<Node> stack = new Stack<Node>();
            stack.push(topElm);
            while (!stack.isEmpty()) {
                Node curElm = stack.pop();
                if (curElm.getNodeType() == type) {
                    retvals.add(curElm);
                }
                List<Node> nodesToProcess = new ArrayList<Node>();

                NodeList childNodes = curElm.getChildNodes();
                for (int i = 0, ll = childNodes.getLength(); i < ll; i++) {
                    Node item = childNodes.item(i);
                    //stack.push((Element) item);
                    nodesToProcess.add(item);
                }
                Collections.reverse(nodesToProcess);
                for (Node node : nodesToProcess) {
                    stack.push(node);
                }
            }
            return retvals;
        }
    }
}

Related

  1. findElement(Element topElm, String localName, String namespace)
  2. findElement(final Element e, final String find)
  3. findElement(final String idValue, final String idTagName, final String tagName, final Element root)
  4. findElementAsString(final Element e, final String find)
  5. findElementWithId(String id, Element root)
  6. findNodeValue(Element firstElement, String name)
  7. getAllElements(Element config, String elementName)
  8. getAllElements(Element element)
  9. getAllElements(Node context)