Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

后端 未结 3 388
不知归路
不知归路 2020-12-02 06:17

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

3条回答
  •  被撕碎了的回忆
    2020-12-02 07:00

    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;
      }
    

提交回复
热议问题