Remove all node s node children

I have a node document of a DOM document. How to delete all child nodes? For instance:

<employee> <one/> <two/> <three/> </employee> 

becomes:

  <employee> </employee> 

I want to remove all employee child nodes.

+8
source share
6 answers
  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 Node children by passing it to Node employees.

-1
source

No need to delete child nodes of child nodes

 public static void removeChilds(Node node) { while (node.hasChildNodes()) node.removeChild(node.getFirstChild()); } 
+41
source
 public static void removeAllChildren(Node node) { for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child)); } 
+1
source
 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()); } 
0
source

Just use:

 Node result = node.cloneNode(false); 

As a 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). 
0
source
 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); } } } 
-1
source

Source: https://habr.com/ru/post/890925/


All Articles