Inconsistency when passing kwarg attribute using cElementTree
According to the ElementTree docs, the interface for Element()
takes a keyword argument attrib
.
class xml.etree.ElementTree.Element(tag, attrib={}, **extra)
This is explained by the following ...
attrib is an optional dictionary, containing element attributes.
This now works for me as described using Python 2.7 and ElementTree. for example
>>> import xml.etree.ElementTree as ET
>>> parent = ET.Element("parent")
>>> attribs = {'age': '20', 'name': 'Steve'}
>>> child = ET.SubElement(parent, "child", attrib=attribs)
>>> ET.dump(parent)
<parent><child age="20" name="Steve" /></parent>
However, when I run the same script but import the implementation cElementTree
, an exception is thrown TypeError
.
File "attrib.py", line 17, in <module>
ET.dump(parent)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1165, in dump
elem.write(sys.stdout)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 821, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 940, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 933, in _serialize_xml
v = _escape_attrib(v, encoding)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1093, in _escape_attrib
_raise_serialization_error(text)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1053, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize {'age': '20', 'name': 'Steve'} (type dict)
What am I missing here? I wonder if I just pass the dictionary attribs
as a positional argument, the cElementTree code works fine.
>>> import xml.etree.cElementTree as ET
>>> parent = ET.Element("parent")
>>> attribs = {'age': '20', 'name': 'Steve'}
>>> child = ET.SubElement(parent, "child", attribs)
>>> ET.dump(parent)
<parent><child age="20" name="Steve" /></parent>
I found a bug referenced on bugs.python.org related to this - but it's closed with doesn't fix the resolution, Why does the C implementation behave differently? Is there any documentation around this that I have missed. Thanks to
source to share
No one has answered this question yet
Check out similar questions: