Can I iterate through a NodeList using for-each in Java?

前端 未结 10 1106
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 00:55

I want to iterate through a NodeList using a for-each loop in Java. I have it working with a for loop and a do-while loop but not for-each.

Node         


        
10条回答
  •  执笔经年
    2020-12-09 01:47

    The workaround for this problem is straight-forward, and, thankfully you have to implements it only once.

    import java.util.*;
    import org.w3c.dom.*;
    
    public final class XmlUtil {
      private XmlUtil(){}
    
      public static List asList(NodeList n) {
        return n.getLength()==0?
          Collections.emptyList(): new NodeListWrapper(n);
      }
      static final class NodeListWrapper extends AbstractList
      implements RandomAccess {
        private final NodeList list;
        NodeListWrapper(NodeList l) {
          list=l;
        }
        public Node get(int index) {
          return list.item(index);
        }
        public int size() {
          return list.getLength();
        }
      }
    }
    

    Once you have added this utility class to your project and added a static import for the XmlUtil.asList method to your source code you can use it like this:

    for(Node n: asList(dom.getElementsByTagName("year"))) {
      …
    }
    

提交回复
热议问题