minidom appendChild confusion

Peter Otten __peter__ at web.de
Fri Sep 23 07:20:55 EDT 2005


Marco wrote:

> Can anyone explain why the following code does not work?
> (I'm using python2.4.)

> # the following code does _not_ work.
> # intended: put child-nodes as children to another node
> 
> from xml.dom.minidom import Document
> doc = Document()
> node1 = doc.createElement('one')
> el1 = doc.createElement('e1')
> el2 = doc.createElement('e1')
> node1.appendChild(el1)
> node1.appendChild(el2)
> assert 2 == len(node1.childNodes) # ok
> 
> doc2 = Document()
> node2 = doc2.createElement('two')
> 
> for el in node1.childNodes:
>     node2.appendChild(el)

A node added to node2's children is implicitly removed from node1's
children. So you are iterating over the node1.childNodes list while
altering it, which typically results in skipping every other item:

>>> a = list("abcde")
>>> for i in a:
...     a.remove(i)
...
>>> a
['b', 'd']

You can avoid that by making a copy of node1.childNodes:

for el in list(node1.childNodes):
    node2.appendChild(el)


> assert 2 == len(node2.childNodes), "node2 has an unexpected number of
> children"

Peter




More information about the Python-list mailing list