【问题标题】:How could I convert a simple XML to CSV using Python?如何使用 Python 将简单的 XML 转换为 CSV?
【发布时间】:2019-02-17 19:19:34
【问题描述】:

这是我的 XML 文件 test.xml:

<nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/nodes_file.xsd">
    <node id="0" x="0.0" y="0.0" type="traffic_light"/> 
    <node id="1" x="0.0" y="500.0" type="priority"/> 
    <node id="2" x="500.0" y="0.0" type="priority"/> 
    <node id="3" x="0.0" y="-500.0" type="priority"/>
    <node id="4" x="-500.0" y="0.0" type="priority"/>

</nodes>

我想将其转换为包含以下列的 CSV 文件: id, x, y, type。所以它会是这样的:

id,x,y,type
0,0.0,0.0,traffic_light
1,0.0,500.0,priority
2,500.0,0.0,priority
3,0.0,-500.0,priority
4,-500.0,0.0,priority

我如何通过 Python 做到这一点?感谢您的关注!

【问题讨论】:

    标签: python xml csv


    【解决方案1】:

    使用xml.etree.ElementTreecsv 模块:

    import xml.etree.ElementTree as et
    import csv
    
    tree = et.parse('node.xml')
    nodes = tree.getroot()
    with open('node.csv', 'w') as ff:
        cols = ['id','x','y','type']
        nodewriter = csv.writer(ff)
        nodewriter.writerow(cols)
        for node in nodes:
            values = [ node.attrib[kk] for kk in cols]
            nodewriter.writerow(values)
    

    【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2017-09-16
    • 2016-12-21
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2019-07-27
    • 2013-03-29
    相关资源
    最近更新 更多