[XML-SIG] Help with removeChild()

Thomas B. Passin tpassin@home.com
Thu, 10 May 2001 08:59:19 -0400

I think your problem is the inverse- the childNodes list ***is*** getting
updated by the DOM after each removal.

[Mike Hammill]

> That is only elements a, c, and e are eliminated.  The code is:
> def trim_dom_more(node):
>     if node.hasChildNodes():
>         for child in node.childNodes:
>             trim_dom_more(child)
>     else:
>         if node.nodeType == node.ELEMENT_NODE:
>             if (not node.hasAttributes()) and (not node.hasChildNodes()):
>                 node.parentNode.removeChild(node)
> I think I understand that the problem is that node.childNodes gets
> and put on the stack, but then after the removeChild, this stacked list is
> re-evaluated so not all children are iterated through.  But how to solve

 Try this:

 def trim_dom_more(node):
     if node.hasChildNodes():
         for child in children:

Now you are iterating through a static copy of the list.  It wouldn't work
if the child nodes could get changed by another thread, but I don't suppose
that's going to happen here.

Or you could do

while node.hasChildNodes():

That would execute slower, though.  But it wouldn't get fooled by any other
activity in the DOM.


Tom P