001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.iterators; 018 019import java.util.Iterator; 020import java.util.NoSuchElementException; 021import java.util.Objects; 022 023import org.w3c.dom.Node; 024import org.w3c.dom.NodeList; 025 026/** 027 * An {@link Iterator} over a {@link NodeList}. 028 * <p> 029 * This iterator does not support {@link #remove()} as a {@link NodeList} does not support 030 * removal of items. 031 * </p> 032 * 033 * @since 4.0 034 * @see NodeList 035 */ 036public class NodeListIterator implements Iterator<Node> { 037 038 /** The original NodeList instance */ 039 private final NodeList nodeList; 040 /** The current iterator index */ 041 private int index; 042 043 /** 044 * Convenience constructor, which creates a new NodeListIterator from 045 * the specified node's childNodes. 046 * 047 * @param node Node, whose child nodes are wrapped by this class. Must not be null 048 * @throws NullPointerException if node is null 049 */ 050 public NodeListIterator(final Node node) { 051 Objects.requireNonNull(node, "node"); 052 this.nodeList = node.getChildNodes(); 053 } 054 055 /** 056 * Constructor, that creates a new NodeListIterator from the specified 057 * {@code org.w3c.NodeList} 058 * 059 * @param nodeList node list, which is wrapped by this class. Must not be null 060 * @throws NullPointerException if nodeList is null 061 */ 062 public NodeListIterator(final NodeList nodeList) { 063 this.nodeList = Objects.requireNonNull(nodeList, "nodeList"); 064 } 065 066 @Override 067 public boolean hasNext() { 068 return nodeList != null && index < nodeList.getLength(); 069 } 070 071 @Override 072 public Node next() { 073 if (nodeList != null && index < nodeList.getLength()) { 074 return nodeList.item(index++); 075 } 076 throw new NoSuchElementException("underlying nodeList has no more elements"); 077 } 078 079 /** 080 * Throws {@link UnsupportedOperationException}. 081 * 082 * @throws UnsupportedOperationException always 083 */ 084 @Override 085 public void remove() { 086 throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator."); 087 } 088}