繁体   English   中英

通过在python中将数据结构写入XML文件来实现TypeError

[英]TypeError by writing data structure to XML file in python

我想使用带有etree库的Python将数据结构写入XML文件。 但是,我收到了一个带有以下消息的TypeError

如果我在命令行中打印数据结构,它看起来很好。 我不确定这个错误是否与我的XML文件有关。 我已经用python2python3执行了脚本。

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)

以下代码有效。
寻找差异。

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree

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>'''

root = ET.fromstring(xml)
tree = ElementTree(root)
tree.write('routes.xml')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM