Home > java > Turn org.w3c.dom.NodeList into Iterable

Turn org.w3c.dom.NodeList into Iterable

I recently posted some reusable code that facilitates reverse iteration over a list in Java.

Here is another potentially useful Java method related to iteration, from my buddy Jordan Armstrong:

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
  /**
   * @param n An XML node list
   * @return A newly created Iterable for the given node list, allowing 
   *         iteration over the nodes in a for-each loop. The iteration 
   *         behavior is undefined if concurrent modification of the node list
   *         occurs.
   */
  public static Iterable<Node> iterable(final NodeList n) {
    return new Iterable<Node>() {

      @Override
      public Iterator<Node> iterator() {

        return new Iterator<Node>() {

          int index = 0;

          @Override
          public boolean hasNext() {
            return index < n.getLength();
          }

          @Override
          public Node next() {
            if (hasNext()) {
              return n.item(index++);
            } else {
              throw new NoSuchElementException();
            }  
          }

          @Override
          public void remove() {
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }
Advertisements
Categories: java
  1. October 5, 2012 at 17:05

    Hi oliver,
    you should read this article about NodeList and Iterable: http://www.jroller.com/agoubard/entry/elementlist_as_replacement_for_nodelist

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: