[XML-SIG] Deep copy of an element from one document to another

Fred L. Drake, Jr. fdrake@acm.org
Tue, 18 Jun 2002 17:48:23 -0400


Mike Olson writes:
 > Right here, you are destroying the list as you walk over it so you end
 > up skipping items.
 > 
 > 1.  Start loop with what is at index 0
 > 2.  Remove the firs thing from the list (with the append child)
 > 3.  Start loop with index of 1 (in the original list this will be the
 > third item)
 > etc.
 > 
 > try this
 > for n in nd.childNodes[:]: rec.appendChild(n)

Another idiom that I like is this:

    n = nd.firstChild
    while n is not None:
        next = n.nextSibling
        rec.appendChild(n)
        n = next

This has the advantage of not creating a separate list.  It is,
unfortunately, more verbose.

Perhaps Python DOMs should implement the iterator protocol:

def _childiter(node):
    n = node.firstChild
    while n is not None:
        next = n.nextSibling
        yeild n
        n = next

class Node:
    ...
    def __iter__(self):
        return _childiter(self)


  -Fred

-- 
Fred L. Drake, Jr.  <fdrake at acm.org>
PythonLabs at Zope Corporation