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 * https://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 * </p>
32 *
33 * @since 4.0
34 * @see NodeList
35 */
36 public class NodeListIterator implements Iterator<Node> {
37
38 /** The original NodeList instance */
39 private final NodeList nodeList;
40
41 /** The current iterator index */
42 private int index;
43
44 /**
45 * Convenience constructor, which creates a new NodeListIterator from
46 * the specified node's childNodes.
47 *
48 * @param node Node, whose child nodes are wrapped by this class. Must not be null
49 * @throws NullPointerException if node is null
50 */
51 public NodeListIterator(final Node node) {
52 Objects.requireNonNull(node, "node");
53 this.nodeList = node.getChildNodes();
54 }
55
56 /**
57 * Constructor, that creates a new NodeListIterator from the specified
58 * {@code org.w3c.NodeList}
59 *
60 * @param nodeList node list, which is wrapped by this class. Must not be null
61 * @throws NullPointerException if nodeList is null
62 */
63 public NodeListIterator(final NodeList nodeList) {
64 this.nodeList = Objects.requireNonNull(nodeList, "nodeList");
65 }
66
67 @Override
68 public boolean hasNext() {
69 return nodeList != null && index < nodeList.getLength();
70 }
71
72 @Override
73 public Node next() {
74 if (nodeList != null && index < nodeList.getLength()) {
75 return nodeList.item(index++);
76 }
77 throw new NoSuchElementException("underlying nodeList has no more elements");
78 }
79
80 /**
81 * Always throws {@link UnsupportedOperationException}.
82 *
83 * @throws UnsupportedOperationException Always thrown.
84 */
85 @Override
86 public void remove() {
87 throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator.");
88 }
89 }