此问题的解决方法很简单,值得庆幸的是,您只需实现一次即可。
import java.util.*;import org.w3c.dom.*;public final class XmlUtil { private XmlUtil(){} public static List<Node> asList(NodeList n) { return n.getLength()==0? Collections.<Node>emptyList(): new NodeListWrapper(n); } static final class NodeListWrapper extends AbstractList<Node> 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(); } }}在将此实用程序类添加到项目中并
static
import为
XmlUtil.asList源代码添加方法的后,您可以像这样使用它:
for(Node n: asList(dom.getElementsByTagName("year"))) { …}


