Python : Data extraction from xml file
<p>Given the following file of <code>xml</code> which stores the values of vehicles trip info. How can I generate a cumulative traveled distance over each time step as a .text file. There is no specific order in the xml, it's all random.    </p>

<pre><code>&lt;tripinfos&gt;
        &lt;tripinfo id="1" depart="1.00" arrival="2" duration="1.00" distance="3"/&gt;
        &lt;tripinfo id="5" depart="2.00" arrival="4" duration="2.00" distance="5"/&gt;
        &lt;tripinfo id="10" depart="5.00" arrival="8" duration="3.00" distance="1"/&gt;
        &lt;tripinfo id="3" depart="3.00" arrival="6" duration="3.00" distance="2"/&gt;
        &lt;tripinfo id="8" depart="8.00" arrival="10" duration="2.00" distance="4"/&gt;
&lt;/tripinfos&gt;
</code></pre>

<p>output.textfile</p>

<pre><code>0 //Time step #0
0
3
3
8
8
10
10
11
11
15
</code></pre>

<p>I ended up using a dict to store each arrival time, and since I know the max arrival time, I can initalize the key with a range.</p>

<pre><code>import xml.etree.ElementTree as ET

filepath = r'tripinfo.xml'
tree = ET.parse(filepath)
root = tree.getroot()
mydict = {k:[] for k in range(7202)}

for trip in root.iter('tripinfo'):
    arrived = int(float(trip.get('arrival')))
    distance = float(trip.get('distance'))
    mydict[arrived].append(distance)

mysum = 0

outputfilepath = 'travelledDuration.txt'
outputfile = open(outputfilepath, 'a')
for i in range(7202):
    distanceList = mydict[i]
    mysum += sum(distanceList)
    outputfile.write(str(mysum)+"\n")
outputfile.close()
</code></pre>

python xml python-2.7