我想使用带有etree库的Python将数据结构写入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)
答案 0 :(得分:0)
下面的代码有效。
寻找差异。
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')