【问题标题】:TypeError by writing data structure to XML file in python通过在python中将数据结构写入XML文件的TypeError
【发布时间】:2019-06-10 00:26:07
【问题描述】:

我想使用 Python 和 etree 库将数据结构写入 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)

【问题讨论】:

    标签: python xml xml-parsing elementtree


    【解决方案1】:

    下面的代码有效。
    寻找差异。

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

    【讨论】:

    • 感谢您的评论。我发现了错误:在第 5 行 ET.SubElement(traffic_root, "trip" ,trip_tag.attrib) 完成了这项工作。
    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多