Can't dump or write an ElementTree element
Asked Answered
E

4

7

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.

Encephaloma answered 30/6, 2011 at 10:52 Comment(0)
M
11

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)
Malvia answered 30/6, 2011 at 11:9 Comment(1)
I wish the etree documentation was as clear as your answerUnchaste
C
5

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>'
Clie answered 30/6, 2011 at 11:9 Comment(0)
S
2

Problem is pretty old but maybe this remark will help someone: 'cannot serialize' can be thrown also when XML object was created with e.g. lxml and .tostring is called from another library, e.g. xml.etree.ElementTree

Example of (dirty) solution (no protection against invalid args shown here)

inxml = elxml.getroot() if hasattr(elxml, 'getroot') else elxml
try:
    from lxml import etree as ETS
    outstr = ETS.tostring(inxml)
except:
    try:
        import xml.etree.cElementTree as ETS
    except:
        import xml.etree.ElementTree as ETS
    outstr = ETS.tostring(inxml)
return outstr
Siqueiros answered 29/8, 2019 at 12:19 Comment(0)
M
1

SubElement's second parameter is a String -- the name of the tag you'd like to add to the root Element. You either want append or insert if you're dealing with Elements.

Mortise answered 30/6, 2011 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.