簡體   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