我有一个DOM文档节点。如何删除其所有子节点?例如:
<employee>
<one/>
<two/>
<three/>
</employee>
变为:
<employee>
</employee>
我想删除employee
的所有子节点。
答案 0 :(得分:41)
无需删除子节点的子节点
public static void removeChilds(Node node) {
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
}
答案 1 :(得分:1)
public static void removeAllChildren(Node node)
{
for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child));
}
答案 2 :(得分:0)
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());
}
答案 3 :(得分:0)
只需使用:
Node result = node.cloneNode(false);
作为文档:
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).
答案 4 :(得分:-1)
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);
}
}
}
这将通过传递员工节点来删除节点的所有子元素。
答案 5 :(得分:-1)
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);
}
}
}