如何使用Python将简单的XML转换为CSV? [英] How could I convert a simple XML to CSV using Python?

查看:60
本文介绍了如何使用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,.所以会是这样的:

I want to convert it to a CSV file which contains the following columns: id, x, y, type. So it would be something like this:

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

How could I do it via Python? Thanks for your attention!

推荐答案

使用csv 模块:

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)

这篇关于如何使用Python将简单的XML转换为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆