我想在 Java 中使用 for-each 循环遍历 NodeList
。我让它使用 for 循环和 do-while 循环,但不是 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());
}
原文由 user2919834 发布,翻译遵循 CC BY-SA 4.0 许可协议
这个问题的解决方法很简单,幸运的是你只需实施一次。
一旦您将此实用程序类添加到您的项目并添加了
static
import
为XmlUtil.asList
方法添加到您的源代码中,您可以像这样使用它: