无法转储或写入 ElementTree 元素
我在输出即使是最简单的元素(树)实例时也遇到问题。如果我在 Python 2.7.1 中尝试以下代码,
>>> from xml.etree.ElementTree import Element, SubElement, tostring
>>> root = Element('parent')
>>> child = Element('child')
>>> SubElement(root, child)
>>> tostring(root)
则会收到错误:
TypeError: cannot serialize <Element 'root' at 0x9a7c7ec> (type 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
SubElement 不将元素作为第二个参数。 API 文档 给出签名,即
第二个参数是子元素的标签(即名称)
ElementTree 文档 提供更多详细信息
要添加子元素,请查看附加内容元素上的方法,例如
SubElement does not take an element as the second parameter. The API docs give the signature as
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.
http://docs.python.org/library /xml.etree.elementtree.html#xml.etree.ElementTree.SubElement
SubElement 的第二个参数是 tag (str) 而不是 Element,它自己创建 Element 实例:
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:
问题很老了,但也许这句话会对某人有所帮助:
当使用例如 lxml 创建 XML 对象并且从另一个库调用 .tostring 时,也可能会抛出“无法序列化”
(脏)解决方案的示例(没有针对此处显示的无效参数的保护)
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)
SubElement
的第二个参数是一个字符串——您要添加到根元素的标签的名称。如果您正在处理Element
,则需要append
或insert
。SubElement
's second parameter is a String -- the name of the tag you'd like to add to the root Element. You either wantappend
orinsert
if you're dealing withElement
s.