I had occasion today to iterate through a list of XML child nodes in Java, as provided by Element.getChildNodes() in the W3C DOM library. For some reason, however, the NodeList object returned does not implement java.lang.Iterable and as such, the pretty new for loop syntax that uses iterators does not work.

I need to do a lot of iterating over these things, so I decided to remedy the situation. Since Java isn't Ruby and I can't just open up the class and add the interface, I had to write a wrapper:

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.UnsupportedOperationException;

public class NodeListIterator implements Iterator, Iterable<Node> {
    private NodeList nodeList_;
    private int index_ = 0;

    public NodeListIterator(NodeList nodeList) {
        nodeList_ = nodeList;
    }

    public Node next() throws NoSuchElementException {
        Node node = nodeList_.item(index_++);
        if (node == null) {
            throw new NoSuchElementException();
        }
        return node;
    }

    public boolean hasNext() {
        return index_ < nodeList_.getLength();
    }

    public NodeListIterator iterator() {
        return this;
    }

    public void remove() throws UnsupportedOperationException{
        throw new UnsupportedOperationException();
    }
}

I wrote this as an inner class on some work stuff which I can't show, so I'm not entirely sure it'll work as-is. If you find any bugs, let me know and I'll fix it.