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