根据ElementTree docs,Element()
的界面需要attrib
个关键字参数。
class xml.etree.ElementTree.Element(tag, attrib={}, **extra)
以下解释......
attrib is an optional dictionary, containing element attributes.
现在这对我有用,如使用Python 2.7和ElementTree所描述的那样。例如
>>> 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>
但是,当我运行相同的脚本但导入cElementTree
实现时,会引发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)
我在这里缺少什么?有趣的是,如果我只是将attribs
字典作为位置参数传递,则cElementTree代码可以正常工作。
>>> 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>
我发现了一个与此相关的bug listed on bugs.python.org - 但它已关闭,无法解决问题。为什么C实现的行为不同?有没有关于这个的文件我错过了。感谢