ElementTree's Element substitution in Python 3

André andre.roberge at gmail.com
Fri Jul 24 13:54:21 EDT 2009


I have a function to replace the content of an ElementTree Element by
that of another one which works using Python 2 but not with Python 3.
I get an assertion error.  The function is as follows:

def replace_element(elem, replacement):
    '''replace the content of an ElementTree Element by that of
another
       one.
    '''
    elem.clear()
    elem.text = replacement.text
    elem.tail = replacement.tail
    elem.tag = replacement.tag
    elem.attrib = replacement.attrib
    elem[:] = replacement[:]

The last line is problematic.  For example, if I do the following
program with Python2.5
###
from xml.etree import ElementTree as et

a = et.Element('a')
b = et.SubElement(a, 'b')
c = et.Element('c')

a[:] = c[:]
###
nothing of note happens - however, doing the same with Python 3.1, I
get the following traceback:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    a[:] = c[:]
  File "/usr/local/py3.1/lib/python3.1/xml/etree/ElementTree.py", line
210, in __setitem__
    assert iselement(element)
AssertionError

======
I would gladly welcome any suggestion for writing a replace_element()
function that works with Python 3.1

André



More information about the Python-list mailing list