0

This is my XML file 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>

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

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

1 Answer 1

2

use xml.etree.ElementTree and csv modules:

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)
Sign up to request clarification or add additional context in comments.

2 Comments

where does [kk] come from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.