开发者

Remove all child nodes of a node

I have a node of DOM document. How can I remove all of its child nodes? For example:

<employee> 
     <one/>
     <two/>
     <three/>
 &开发者_开发问答lt;/employee>

Becomes:

   <employee>
   </employee>

I want to remove all child nodes of 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));
}


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).


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());
}


    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.


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);  
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜