首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:迭代org.w3c.dom.Document中所有元素的最有效方法?

Java:迭代org.w3c.dom.Document中所有元素的最有效方法?
EN

Stack Overflow用户
提问于 2011-03-22 12:55:16
回答 2查看 179.1K关注 0票数 76

在Java中遍历所有DOM元素的最有效方法是什么?

如下所示,但对于当前org.w3c.dom.Document上的每个DOM元素

代码语言:javascript
复制
for(Node childNode = node.getFirstChild(); childNode!=null;){
    Node nextChild = childNode.getNextSibling();
    // Do something with childNode, including move or delete...
    childNode = nextChild;
}
EN

回答 2

Stack Overflow用户

发布于 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的第二种方式可能是最好的,因为它倾向于使用更扁平的、可预测的内存模型。

票数 37
EN

Stack Overflow用户

发布于 2014-02-05 19:24:02

我最近也遇到了这个问题。这是我的解决方案。我想避免递归,所以我使用了while循环。

由于列表中任意位置的添加和删除,我选择了LinkedList实现。

代码语言:javascript
复制
/* 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;
  }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5386991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档