Java 删除一个节点的所有子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6411687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:44:11 来源:igfitidea点击:
Remove all child nodes of a node
提问by akshay
I have a node of DOM document. How can I remove all of its child nodes? For example:
我有一个 DOM 文档节点。如何删除其所有子节点?例如:
<employee>
<one/>
<two/>
<three/>
</employee>
Becomes:
变成:
<employee>
</employee>
I want to remove all child nodes of employee
.
我想删除employee
.
采纳答案by Hunter McMillen
public static void removeAll(Node node)
{
for(Node n : node.getChildNodes())
{
if(n.hasChildNodes()) //edit to remove children of children
{
removeAll(n);
node.removeChild(n);
}
else
node.removeChild(n);
}
}
}
This will remove all the child elements of a Node by passing the employee node in.
这将通过传入员工节点来删除节点的所有子元素。
回答by leoismyname
private static void removeAllChildNodes(Node node) {
NodeList childNodes = node.getChildNodes();
int length = childNodes.getLength();
for (int i = 0; i < length; i++) {
Node childNode = childNodes.item(i);
if(childNode instanceof Element) {
if(childNode.hasChildNodes()) {
removeAllChildNodes(childNode);
}
node.removeChild(childNode);
}
}
}
回答by Venkata Raju
public static void removeAllChildren(Node node)
{
for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child));
}
回答by kop
No need to remove child nodes of child nodes
无需移除子节点的子节点
public static void removeChilds(Node node) {
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
}
回答by Mustapha Charboub
public static void removeAllChildren(Node node) {
NodeList nodeList = node.getChildNodes();
int i = 0;
do {
Node item = nodeList.item(i);
if (item.hasChildNodes()) {
removeAllChildren(item);
i--;
}
node.removeChild(item);
i++;
} while (i < nodeList.getLength());
}
回答by Google New
Just use:
只需使用:
Node result = node.cloneNode(false);
As document:
作为文件:
Node cloneNode(boolean deep)
deep - If true, recursively clone the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element).