1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.collections4.iterators; 18 19 import java.util.Iterator; 20 import java.util.NoSuchElementException; 21 import java.util.Objects; 22 23 import org.w3c.dom.Node; 24 import org.w3c.dom.NodeList; 25 26 /** 27 * An {@link Iterator} over a {@link NodeList}. 28 * <p> 29 * This iterator does not support {@link #remove()} as a {@link NodeList} does not support 30 * removal of items. 31 * 32 * @since 4.0 33 * @see NodeList 34 */ 35 public class NodeListIterator implements Iterator<Node> { 36 37 /** The original NodeList instance */ 38 private final NodeList nodeList; 39 /** The current iterator index */ 40 private int index; 41 42 /** 43 * Convenience constructor, which creates a new NodeListIterator from 44 * the specified node's childNodes. 45 * 46 * @param node Node, whose child nodes are wrapped by this class. Must not be null 47 * @throws NullPointerException if node is null 48 */ 49 public NodeListIterator(final Node node) { 50 Objects.requireNonNull(node, "node"); 51 this.nodeList = node.getChildNodes(); 52 } 53 54 /** 55 * Constructor, that creates a new NodeListIterator from the specified 56 * {@code org.w3c.NodeList} 57 * 58 * @param nodeList node list, which is wrapped by this class. Must not be null 59 * @throws NullPointerException if nodeList is null 60 */ 61 public NodeListIterator(final NodeList nodeList) { 62 this.nodeList = Objects.requireNonNull(nodeList, "nodeList"); 63 } 64 65 @Override 66 public boolean hasNext() { 67 return nodeList != null && index < nodeList.getLength(); 68 } 69 70 @Override 71 public Node next() { 72 if (nodeList != null && index < nodeList.getLength()) { 73 return nodeList.item(index++); 74 } 75 throw new NoSuchElementException("underlying nodeList has no more elements"); 76 } 77 78 /** 79 * Throws {@link UnsupportedOperationException}. 80 * 81 * @throws UnsupportedOperationException always 82 */ 83 @Override 84 public void remove() { 85 throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator."); 86 } 87 }