簡體   English   中英

如何使用 Python 將簡單的 XML 轉換為 CSV?

[英]How could I convert a simple XML to CSV using Python?

這是我的 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 做到這一點? 感謝您的關注!

使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM