Extract specific information from XML (Google Distance Matrix API)
<p>Here is my XML output:</p>

<pre><code>&lt;DistanceMatrixResponse&gt;
&lt;status&gt;OK&lt;/status&gt;
&lt;origin_address&gt;
868-978 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
&lt;/origin_address&gt;
&lt;destination_address&gt;
980-1060 Middle Tennessee Blvd, Murfreesboro, TN 37130, USA
&lt;/destination_address&gt;
&lt;row&gt;
&lt;element&gt;
&lt;status&gt;OK&lt;/status&gt;
&lt;duration&gt;
&lt;value&gt;19&lt;/value&gt;
&lt;text&gt;1 min&lt;/text&gt;
&lt;/duration&gt;
&lt;distance&gt;
&lt;value&gt;154&lt;/value&gt;
&lt;text&gt;0.1 mi&lt;/text&gt;
&lt;/distance&gt;
&lt;/element&gt;
&lt;/row&gt;
&lt;/DistanceMatrixResponse&gt;
</code></pre>

<p>I am trying to use Python to save this XML from the web locally (this part is complete). After the file is saved, I want to extract the 'duration' value (of 19, in this case) and the 'distance' value (of 154, in this case). </p>

<p>I just can't seem to figure out how to read and extract the necessary information from this XML. I have tried working with ElementTree and trying to implement others solutions from stackoverflow, with no luck. I'm about 3 hours into what should be a quick process.</p>

<p>Here is my code as it sits now:</p>

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

## import XML and save it out
url = "https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&amp;origins=35.827581,-86.394077&amp;destinations=35.827398,-86.392381&amp;key=mygooglemapsAPIkey"
s = urllib2.urlopen(url)
contents = s.read()
file = open("export.xml", 'w')
file.write(contents)
file.close()
## finish saving the XML


element_tree = ET.parse("export.xml")
root = element_tree.getroot()
agreement = root.find("duration").text
print agreement


## open XML and save out travel time in seconds
xmlfile = 'export.xml'
element_tree = ET.parse(xmlfile)
root = element_tree.getroot()
agreement = root.findall("duration").text
print agreement
</code></pre>

<p>Current error message is: AttributeError: 'Nonetype' object has no attribute 'text'</p>

<p>I know the code is incomplete to grab both the duration and distance, but I am just trying to get something working at this point!</p>

<p>Just use <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#example" rel="nofollow">XPath queries</a>:</p>

<pre><code>duration = tree.find('.//duration/value').text
distance = tree.find('.//distance/value').text
</code></pre>

<p>Here's a nice XPath tutorial: <a href="http://zvon.org/comp/r/tut-XPath_1.html" rel="nofollow">http://zvon.org/comp/r/tut-XPath_1.html</a>.</p>

python xml elementtree