Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't dump or write an ElementTree element

I'm having a problem outputting even the simplest Element(Tree) instances. If I try the following code in Python 2.7.1

>>> from xml.etree.ElementTree import Element, SubElement, tostring
>>> root = Element('parent')
>>> child = Element('child')
>>> SubElement(root, child)
>>> tostring(root)

I get an error:

TypeError: cannot serialize <Element 'root' at 0x9a7c7ec> (type Element)

I must be doing something wrong but the documentation isn't pointing me at anything obvious.

like image 868
andy47 Avatar asked Jun 30 '11 10:06

andy47


Video Answer


2 Answers

SubElement does not take an element as the second parameter. The API docs give the signature as

SubElement(parent, tag, attrib={}, **extra)

i.e. the second parameter is the tag (i.e. name) of the sub element

The ElementTree docs give more detail

To add a child element look at the append method on Element e.g.

root.append(child)
like image 96
mmmmmm Avatar answered Sep 25 '22 01:09

mmmmmm


http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement

SubElement's second argument is tag (str) not Element, it creates Element instance by itself:

>>> SubElement(root, 'child')
0: <Element 'child' at 0x1f2dfb0>
>>> tostring(root)
1: '<parent><child /></parent>'
like image 44
Pill Avatar answered Sep 25 '22 01:09

Pill