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'm sure there's a better solution that uses an xml library, but here's an easy one</p>

<pre><code>import numpy as np

a = open('file.xml')
lines = a.readlines()

my_arr = np.zeros((len(lines)-2,2))
for i in range(len(lines[1:-1])):
    contents=lines[i+1].split('\"')
    my_arr[i,0]=(eval(contents[5]))
    my_arr[i,1]=(eval(contents[9]))

#Now sort according to arrival times
my_arr = (my_arr[my_arr[:,0].argsort()])
print(my_arr)

final_output=[]
cum_dist=0
last_index=0

for i in range(int(my_arr[-1,0])+1):
    if(i == my_arr[last_index,0]):
        cum_dist+=my_arr[last_index,1]
        last_index+=1
    final_output.append(int(cum_dist))

print(final_output)
np.savetxt('outputfile.txt',np.array(final_output), newline=',',fmt='%s')
a.close()
</code></pre>

<p>Your output is </p>

<pre><code>[[  2.   3.]
 [  4.   5.]
 [  6.   2.]
 [  8.   1.]
 [ 10.   4.]]
[0, 0, 3, 3, 8, 8, 10, 10, 11, 11, 15]
</code></pre>

python xml python-2.7