Remove all child nodes of a node

28,087

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

This will remove all the child elements of a Node by passing the employee node in.

Solution 2

No need to remove child nodes of child nodes

public static void removeChilds(Node node) {
    while (node.hasChildNodes())
        node.removeChild(node.getFirstChild());
}

Solution 3

public static void removeAllChildren(Node node)
{
  for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child));
}

Solution 4

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).
Share:
28,087
akshay
Author by

akshay

Updated on July 16, 2020

Comments

  • akshay
    akshay almost 4 years

    I have a node of DOM document. 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.