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>Here I offer a partial solution to your problem.</p>

<pre><code># import some packages
from numpy import array
import xml.etree.ElementTree as et

# init some lists
ids=[]
depart=[]
arrival=[]
duration=[]
distance=[]

# prep the xml document
xmltxt = """
    &lt;root&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="3" depart="3.00" arrival="6" duration="3.00" distance="2"/&gt;
        &lt;tripinfo id="10" depart="5.00" arrival="8" duration="3.00" distance="1"/&gt;
        &lt;tripinfo id="8" depart="8.00" arrival="10" duration="2.00" distance="4"/&gt;
    &lt;/root&gt;
"""

# parse the xml text
xmldoc = et.fromstring(xmltxt)

# extract and output tripinfo attributes
# collect them into lists
for item in xmldoc.iterfind('tripinfo'):
    att=item.attrib
    ids.append(int(att['id']))
    depart.append(float(att['depart']))
    arrival.append(float(att['arrival']))
    duration.append(float(att['duration']))
    distance.append(float(att['distance']))

# put lists into an np.array
# and transpose it    
arr=array([ids, depart, arrival, duration, distance]).T

# sort array by 'depart' column. (index=1)
arr = arr[arr[:,1].argsort()]

sumdist=0
dept=0
print "depart: %s; Sum_dist= %s" % ( dept, sumdist )
for ea in arr:
    sumdist += ea[4] # distance
    dept = ea[1]  # depart
    # get 'arrival', 'duration' here, so that
    # you can use them to manipulate and get your exact solution
    print "depart: %s; Sum_dist= %s" % ( dept, sumdist )
</code></pre>

<p>The output is</p>

<pre><code>depart: 0; Sum_dist= 0
depart: 1.0; Sum_dist= 3.0
depart: 2.0; Sum_dist= 8.0
depart: 3.0; Sum_dist= 10.0
depart: 5.0; Sum_dist= 11.0
depart: 8.0; Sum_dist= 15.0
</code></pre>

python xml python-2.7