Удалить все дочерние узлы узла - PullRequest
8 голосов
/ 20 июня 2011

У меня есть узел документа DOM.Как я могу удалить все его дочерние узлы?Например:

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

становится:

   <employee>
   </employee>

Я хочу удалить все дочерние узлы employee.

Ответы [ 6 ]

41 голосов
/ 28 декабря 2013

Нет необходимости удалять дочерние узлы дочерних узлов

public static void removeChilds(Node node) {
    while (node.hasChildNodes())
        node.removeChild(node.getFirstChild());
}
1 голос
/ 21 марта 2013
public static void removeAllChildren(Node node)
{
  for (Node child; (child = node.getFirstChild()) != null; node.removeChild(child));
}
0 голосов
/ 16 июля 2019

Просто используйте:

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).
0 голосов
/ 07 сентября 2018
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 голосов
/ 07 марта 2013
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 голосов
/ 20 июня 2011
    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);
        }
    }
}

Это удалит все дочерние элементы узла, передав узел сотрудника внутрь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...