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
The validated solution is very useful, but here I share an improved solution based on the valid one, this helps you iterate as well, but easy to use, and secure:
public class XMLHelper {
private XMLHelper() { }
public static List getChildNodes(NodeList l) {
List children = Collections.emptyList();
if (l != null && l.getLength() > 0) {
if (l.item(0) != null && l.item(0).hasChildNodes()) {
children = new NodeListWrapper(l.item(0).getChildNodes());
}
}
return children;
}
public static List getChildNodes(Node n) {
List children = Collections.emptyList();
if (n != null && n.hasChildNodes()) {
NodeList l = n.getChildNodes();
if (l != null && l.getLength() > 0) {
children = new NodeListWrapper(l);
}
}
return children;
}
private 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();
}
}
}
Usage:
for (Node inner : XMLHelper.getChildNodes(node)) { ... }
Thanks @Holger.