DOM要素は、getElementsByTagName()などから作成されたNodeListを反復処理しながら(JavaScript経由で)削除され、要素はNodeListから消えます。これにより、NodeListの正しい反復がより難しくなります。その後
public class IteratableNodeList implements Iterable<Node> {
final NodeList nodeList;
public IteratableNodeList(final NodeList _nodeList) {
nodeList = _nodeList;
}
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
private int index = -1;
private Node lastNode = null;
private boolean isCurrentReplaced() {
return lastNode != null && index < nodeList.getLength() &&
lastNode != nodeList.item(index);
}
@Override
public boolean hasNext() {
return index + 1 < nodeList.getLength() || isCurrentReplaced();
}
@Override
public Node next() {
if (hasNext()) {
if (isCurrentReplaced()) {
// It got removed by a change in the DOM.
lastNode = nodeList.item(index);
} else {
lastNode = nodeList.item(++index);
}
return lastNode;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Stream<Node> stream() {
Spliterator<Node> spliterator =
Spliterators.spliterator(iterator(), nodeList.getLength(), 0);
return StreamSupport.stream(spliterator, false);
}
}
このようにそれを使用します。sienceのための幸せ少しkotlinバージョンを追加 new IteratableNodeList(doc.getElementsByTagName(elementType)).forEach(...)
Iterableインターフェイスを実装していないため、NodeListにforeachループを使用することはできません。 nodeList.getLengthを使用してforループまたはwhileループを使用するオプションのみです。 http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NodeList.html –
これは疑問な質問に接するものですが、私はw3cの使用を恥ずかしく思っていますJava標準ライブラリのもの。 IMOそれは熱い混乱で、XMLパースライブラリがはるかに優れています。 – Jazzepi
+ Jazzepi古いトピックだけど、どのXML解析ライブラリをお勧めしますか?このw3cライブラリが単純で一般的なイテレータを提供していないという事実は、「詳細」ですが、(ライブラリの選択がこの点よりも複雑になる可能性がある場合でも) –