我可以在Java中使用for-each遍历NodeList吗? [英] Can I iterate through a NodeList using for-each in Java?

查看:2207
本文介绍了我可以在Java中使用for-each遍历NodeList吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中使用for-each循环遍历 NodeList 。我让它使用for循环和do-while循环,但不是for-each。

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.

NodeList nList = dom.getElementsByTagName("year");
do {
    Element ele = (Element) nList.item(i);
    list.add(ele.getElementsByTagName("MonthId").item(0).getTextContent());
    i++;
} while (i < nList.getLength());

NodeList nList = dom.getElementsByTagName("year");

for (int i = 0; i < nList.getLength(); i++) {
    Element ele = (Element) nList.item(i);
    list.add(ele.getElementsByTagName("MonthId").item(0).getTextContent());
}


推荐答案

此问题的解决方法是直截了当,谢天谢地,你只需要实现一次。

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

添加此实用程序后您的项目的类,并为 XmlUtil.asList static import $ c>源代码的方法你可以这样使用它:

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"))) {
  …
}

这篇关于我可以在Java中使用for-each遍历NodeList吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆