[英]Remove all child nodes of a node
I have a node of DOM document. 我有一个DOM文档的节点。 How can I remove all of its child nodes? 如何删除其所有子节点? For example: 例如:
<employee>
<one/>
<two/>
<three/>
</employee>
Becomes: 变为:
<employee>
</employee>
I want to remove all child nodes of employee
. 我想删除employee
所有子节点。
No need to remove child nodes of child nodes 无需删除子节点的子节点
public static void removeChilds(Node node) {
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
}
public static void removeAllChildren(Node node)
{
for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child));
}
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());
}
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).
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);
}
}
}
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. 这将通过传递雇员节点来删除节点的所有子元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.