Nếu hiện tại Phần tử DOM được loại bỏ (thông qua JavaScript) trong khi lặp lại một NodeList (được tạo từ getElementsByTagName() và có thể là các phần tử khác), phần tử sẽ biến mất khỏi NodeList. Điều này làm cho việc lặp lại chính xác NodeList phức tạp hơn.
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);
}
}
Sau đó sử dụng nó như thế này: new IteratableNodeList(doc.getElementsByTagName(elementType)). stream().filter(...)
Hoặc: new IteratableNodeList(doc.getElementsByTagName(elementType)).forEach(...)
Bạn không thể sử dụng vòng lặp foreach cho NodeList vì nó không thực hiện giao diện Iterable. Chỉ có tùy chọn bạn có nó để sử dụng vòng lặp for hoặc while khi sử dụng nodeList.getLength. http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NodeList.html –
Trong khi điều này là tiếp tuyến với câu hỏi bạn đang hỏi, tôi sẽ tránh xa việc sử dụng w3c công cụ từ thư viện chuẩn Java. IMO đó là một mớ hỗn độn nóng và có nhiều thư viện phân tích cú pháp XML tốt hơn trên mạng. – Jazzepi
+ Jazzepi Tôi biết đó là chủ đề cũ nhưng bạn đề xuất thư viện phân tích cú pháp XML nào?NB Thực tế là thư viện w3c này không cung cấp một Iterator đơn giản và chung chung là một "chi tiết" nhưng trông giống như một đối số khác chống lại công cụ này (ngay cả khi sự lựa chọn của một thư viện có thể phức tạp hơn điểm này). –