如何使用Python将简单的XML转换为CSV?

时间:2018-09-13 05:31:33

标签: python xml csv

这是我的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做到这一点?感谢您的关注!

1 个答案:

答案 0 :(得分: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)