TypeError:无法序列化x.x(类型float)(Elementtree)

时间:2018-11-19 11:49:43

标签: python python-3.x 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库-额外的库似乎已经过时了,特别是当可能存在更现代的解决方案时< / p>

2 个答案:

答案 0 :(得分:2)

有趣。我看到它无法与float一起使用,因为_escape_cdata函数使用in运算符(if "&" in text)。

此外,docstring for the text attribute表示它是stringNonedocumentation说,“值通常是字符串,但可以是任何特定于应用程序的对象”,我发现这具有误导性。

如果解析 XML文档时需要获取其他类型,建议您使用lxml.objectify

答案 1 :(得分:0)

必须text设置为文本值:

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

简而言之,text仅可以存储文本-无法用信号表示文本节点存储另一种类型。任何其他类型都必须序列化以存储,并反序列化以使用。

请注意,浮点数是一种原始类型,仍然按原义存储为文字'0.3'。您可以轻松地将其转换回去:

>>> print(el.text)
'0.3'
>>> print(float(el.text))
0.3

请记住,XML是一种文本格式-它只能存储文本。如果需要其他数据类型,则必须定义如何将文本解释为目标类型。例如,您可以使用XML Schema Definition (XSD)将字段定义为xs:integer。您也可以在文字中嵌入类型标记-例如存储f0.3i7331来标记浮点数和整数。但是,所有这些都需要一个解析器,该解析器即使对于XSD也知道这种约定。