Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

dom

xml

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()); } 
like image 726
user2919834 Avatar asked Oct 25 '13 11:10

user2919834


People also ask

Can you use forEach on a NodeList?

forEach() The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

Is a NodeList iterable?

NodeList and DOMTokenList should have [Symbol. iterator] because they're iterable.

What is the difference between HTMLCollection and NodeList?

An HTMLCollection is a collection of document elements. A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.


1 Answers

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

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"))) {   … } 
like image 178
Holger Avatar answered Oct 19 '22 23:10

Holger