python xml dom help please

Andrew Clover and-google at doxdesk.com
Mon Nov 24 10:20:24 EST 2003


spam.meplease at ntlworld.com (deglog) wrote:
 
> def deepen(nodeList):
>   for node in nodeList:
>     [...]
>     node.previousSibling.appendChild(node)      

Bzzt: destructive iteration gotcha.

DOM NodeLists are 'live': when you move a child Element out of the parent,
it no longer exists in the childNodes list. So in the example:

  <a/>
  <b/>
  <c/>

the first element (a) cannot be moved and is skipped; the second element (b)
is moved into its previousSibling (a); the third element... wait, there is no
third element any more because (c) is now the second element. So the loop
stops.

A solution would be to make a static copy of the list beforehand. There's no
standard-DOM way of doing that and the Python copy() method is not guaranteed
to work here, so use a list comprehension or map:

  identity= lambda x: x
  for node in map(identity, nodeList):
    ...

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/




More information about the Python-list mailing list