minidom appendChild confusion

M

Marco

Hello!

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


Cheers, Marco

--

# 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)

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

Peter Otten

Marco said:
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.remove(i)
....['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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top