TypeError: cannot serialize x.x (type float) (Elementtree)

TypeError: cannot serialize x.x (type float) (Elementtree)

我正在尝试使用 python 3.6 打印 ElementTree。这是我的代码的可重现示例:

from xml.etree import ElementTree as ET
root = ET.Element('gpx')
el = ET.SubElement(root, 'test')
el.text = 0.3
print(ET.dump(root))

错误信息是:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1177, in dump
    elem.write(sys.stdout, encoding="unicode")
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
    short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
    short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
    write(_escape_cdata(text))
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1074, in _escape_cdata
    _raise_serialization_error(text)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1057, in _raise_serialization_error
    "cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 0.3 (type float)

序列化 float 类型一定是很常见的事情,但我找不到关于如何做到这一点的满意答案 - 标准方法是什么?

研究:

我可以在堆栈溢出上找到 one question,但它建议将浮点数转换为字符串,我需要输出为数字。

google 论坛上有一个关于此的 old discussion,但这是 10 年前的事了,涉及到使用 simplejson 库——一个额外的库似乎有点过分了,尤其是当有可能是更现代的解决方案

有意思。我发现它不适用于 float,因为 _escape_cdata 函数使用 in 运算符 (if "&" in text)。

此外,docstring for the text attribute indicates that it is either a string or None. The documentation 说的是 "values are usually strings but may be any application-specific object",我认为这是误导。

如果你在解析一个XML文档时需要获取其他类型,我推荐你使用lxml.objectify