akshay
akshay

Reputation: 5285

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/>
 </employee>

Becomes:

   <employee>
   </employee>

I want to remove all child nodes of employee.

Upvotes: 15

Views: 31445

Answers (6)

Google New
Google New

Reputation: 107

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

Upvotes: 1

Mustapha Charboub
Mustapha Charboub

Reputation: 849

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

Upvotes: -1

kop
kop

Reputation: 611

No need to remove child nodes of child nodes

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

Upvotes: 57

Venkata Raju
Venkata Raju

Reputation: 5215

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

Upvotes: 1

leoismyname
leoismyname

Reputation: 407

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

Upvotes: -1

Hunter McMillen
Hunter McMillen

Reputation: 61540

    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.

Upvotes: -1

Related Questions