What is the most efficient way to iterate through all DOM elements in Java?
Something like this but for every single DOM elements on current org.w3c.dom.Docume
I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.
Because of the adds and removes in arbitrary places on the list,
I went with the LinkedList implementation.
/* traverses tree starting with given node */
private static List traverse(Node n)
{
return traverse(Arrays.asList(n));
}
/* traverses tree starting with given nodes */
private static List traverse(List nodes)
{
List open = new LinkedList(nodes);
List visited = new LinkedList();
ListIterator it = open.listIterator();
while (it.hasNext() || it.hasPrevious())
{
Node unvisited;
if (it.hasNext())
unvisited = it.next();
else
unvisited = it.previous();
it.remove();
List children = getChildren(unvisited);
for (Node child : children)
it.add(child);
visited.add(unvisited);
}
return visited;
}
private static List getChildren(Node n)
{
List children = asList(n.getChildNodes());
Iterator it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
private static List asList(NodeList nodes)
{
List list = new ArrayList(nodes.getLength());
for (int i = 0, l = nodes.getLength(); i < l; i++)
list.add(nodes.item(i));
return list;
}