【发布时间】:2019-06-10 00:26:07
【问题描述】:
我想使用 Python 和 etree 库将数据结构写入 XML 文件。但是,我收到了 TypeError 的以下消息:
如果我在命令行中打印数据结构,它看起来很好。我不确定这个错误是否与我的 XML 文件有关。我已经使用python2 和python3 执行了脚本。
root = ET.parse(args.filename).getroot()
taxi_root = ET.Element("routes")
for trip_tag in root.iter('trip'):
ET.SubElement(taxi_root, trip_tag)
logging.warning(trip_tag, trip_tag.attrib)
print(trip_tag, trip_tag.attrib)
taxi_tree = ET.ElementTree(taxi_root)
taxi_tree.write("taxi_trips.xml",xml_declaration=True)
给定的 XML 文件如下所示:
<routes>
<trip id="randUni1151:1" type="random" depart="97.00" departPos="34.32" arrivalPos="45.48" arrivalSpeed="0.00" from="-319544709#1" to="25430299#5"/>
<trip id="randUni1922:1" type="random" depart="193.00" departPos="54.02" arrivalPos="134.49" arrivalSpeed="0.00" from="-166643442#0" to="60233456"/>
</routes>
我只想将数据结构写入文件,但收到了这条消息。
Traceback (most recent call last):
File "filter_Throughput_Traffic.py", line 40, in <module>
print(ET.tostring(taxi_root, encoding='utf8').decode('utf8'))
File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 817, in write
self._root, encoding, default_namespace
File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 886, in _namespaces
_raise_serialization_error(tag)
File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 1052, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize <Element 'trip' at 0x103d4c750> (type Element)
【问题讨论】:
标签: python xml xml-parsing elementtree