在遍历NodeList时删除DOM节点 [英] Removing DOM nodes when traversing a NodeList
问题描述
我将使用以下代码删除XML文档中的某些元素:
I'm about to delete certain elements in an XML document, using code like the following:
NodeList nodes = ...;
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element)nodes.item(i);
if (certain criteria involving Element e) {
e.getParentNode().removeChild(e);
}
}
这会干扰NodeList的正确遍历吗?有其他注意事项吗?如果这是完全错误的,那么正确的方法是什么?
Will this interfere with proper traversal of the NodeList? Any other caveats with this approach? If this is totally wrong, what's the proper way to do it?
推荐答案
因此,考虑到在遍历NodeList时删除节点导致NodeList被更新以反映新的现实,我假设我的索引将变得无效,这将不起作用。
So, given that removing nodes while traversing the NodeList will cause the NodeList to be updated to reflect the new reality, I assume that my indices will become invalid and this will not work.
所以,似乎解决方案是保持跟踪要遍历的元素,然后删除它们,一旦NodeList不再使用。
So, it seems the solution is to keep track of the elements to delete during the traversal, and delete them all afterward, once the NodeList is no longer used.
NodeList nodes = ...;
Set<Element> targetElements = new HashSet<Element>();
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element)nodes.item(i);
if (certain criteria involving Element e) {
targetElements.add(e);
}
}
for (Element e: targetElements) {
e.getParentNode().removeChild(e);
}
这篇关于在遍历NodeList时删除DOM节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!