ElementTree's Element substitution in Python 3

André andre.roberge at gmail.com
Fri Jul 24 21:07:32 CEST 2009


Sorry for replying to myself ...  the following seems to be a working
solution to my original problem.
On Jul 24, 2:54 pm, André <andre.robe... at gmail.com> wrote:
> 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[:]
>

Use instead:

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
    try:
        elem[:] = replacement[:]  # works with Python 2.x (fast) but
not 3.x
    except AssertionError:
        del elem[:]
        for child in replacement:
            elem.append(child)


André



More information about the Python-list mailing list