在Java中遍历所有DOM元素的最有效方法是什么?
如下所示,但对于当前org.w3c.dom.Document上的每个DOM元素
for(Node childNode = node.getFirstChild(); childNode!=null;){
Node nextChild = childNode.getNextSibling();
// Do something with childNode, including move or delete...
childNode = nextChild;
}发布于 2012-10-05 05:28:08
for (int i = 0; i < nodeList.getLength(); i++)
更改为
for (int i = 0, len = nodeList.getLength(); i < len; i++)
来提高效率。
javanna的第二种方式可能是最好的,因为它倾向于使用更扁平的、可预测的内存模型。
发布于 2014-02-05 19:24:02
我最近也遇到了这个问题。这是我的解决方案。我想避免递归,所以我使用了while循环。
由于列表中任意位置的添加和删除,我选择了LinkedList实现。
/* traverses tree starting with given node */
private static List<Node> traverse(Node n)
{
return traverse(Arrays.asList(n));
}
/* traverses tree starting with given nodes */
private static List<Node> traverse(List<Node> nodes)
{
List<Node> open = new LinkedList<Node>(nodes);
List<Node> visited = new LinkedList<Node>();
ListIterator<Node> it = open.listIterator();
while (it.hasNext() || it.hasPrevious())
{
Node unvisited;
if (it.hasNext())
unvisited = it.next();
else
unvisited = it.previous();
it.remove();
List<Node> children = getChildren(unvisited);
for (Node child : children)
it.add(child);
visited.add(unvisited);
}
return visited;
}
private static List<Node> getChildren(Node n)
{
List<Node> children = asList(n.getChildNodes());
Iterator<Node> it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
private static List<Node> asList(NodeList nodes)
{
List<Node> list = new ArrayList<Node>(nodes.getLength());
for (int i = 0, l = nodes.getLength(); i < l; i++)
list.add(nodes.item(i));
return list;
}https://stackoverflow.com/questions/5386991
复制相似问题