问题描述
我正在使用以下代码从XMl文件中删除多个元素.
I am using following code to remove multiple elements from XMl file.
NodeList removeNodeList = doc.getElementsByTagName("server1");
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < removeNodeList.getLength(); i++) {
rootElement.removeChild(removeNodeList.item(i));
}
但是删除一个元素后,它就退出了循环.有什么问题.
But after removing one element it is coming out of loop. What is the issue.
以下是我的XML文件内容.
Following is my XML file content.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<start>
<category name="server1"/>
<category name="server2"/>
<server1 name="serverName1" value="serverValue"/>
<server1 name="serverName1" value="serverValue"/>
<server2 name="serverName2" value="serverValue"/>
</start>
推荐答案
我找到了解决方法:
让我详细解释问题所在.
Let me explain what was the problem in detail.
NodeList removeNodeList = doc.getElementsByTagName("server1");
removeNodeList.getLength()
将返回2,因为有2个节点的节点名称为server1
,然后在执行rootElement.removeChild(removeNodeList.item(i));
然后检查for loop
条件i.e.
后,i
的值为1
,而removeNodeList.getLength()
返回1
因为现在只有1个节点名称为server1
的节点保留在DOM document
中,并且此情况由于1 < 1 is false
NodeList removeNodeList = doc.getElementsByTagName("server1");
removeNodeList.getLength()
will return 2 as there are 2 nodes with nodeName server1
then after executing rootElement.removeChild(removeNodeList.item(i));
and then checking for loop
condition i.e.
the value of i
is 1
and removeNodeList.getLength()
returns 1
as now only 1 node with nodeName server1
is remaining in DOM document
and this condition was failing as 1 < 1 is false
所以我遵循以下方法:
一旦不再使用NodeList,请删除所有元素.
Delete all the elements afterwards once the NodeList is no longer used.
NodeList nodes = doc.getElementsByTagName(elementName);
Set<Element> targetElements = new HashSet<Element>();
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element)nodes.item(i);
targetElements.add(e);
}
for (Element e: targetElements) {
e.getParentNode().removeChild(e);
}
这篇关于removeChild()方法正在中断循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!