Parsing Weather XML with Python
<p>I'm a beginner but with a lot of effort I'm trying to parse some data about the weather from an .xml file called "weather.xml" which looks like this:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Weather&gt;
&lt;locality name="Rome" alt="21"&gt;
    &lt;situation temperature="18Â°C" temperatureF="64,4Â°F" humidity="77%" pression="1016 mb" wind="5 SSW km/h" windKN="2,9 SSW kn"&gt;
        &lt;description&gt;clear sky&lt;/description&gt;
        &lt;lastUpdate&gt;17:45&lt;/lastUpdate&gt;
        /&gt;
    &lt;/situation&gt;
    &lt;sun sunrise="6:57" sunset="18:36" /&gt;
&lt;/locality&gt;
</code></pre>

<p>I parsed some data from this XML and this is how my Python code looks now:</p>

<pre><code>#!/usr/bin/python

from xml.dom import minidom
xmldoc = minidom.parse('weather.xml')

entry_situation = xmldoc.getElementsByTagName('situation')
entry_locality = xmldoc.getElementsByTagName('locality')

print entry_locality[0].attributes['name'].value
print "Temperature: "+entry_situation[0].attributes['temperature'].value
print "Humidity: "+entry_situation[0].attributes['humidity'].value
print "Pression: "+entry_situation[0].attributes['pression'].value
</code></pre>

<p>It's working fine but if I try to parse data from "description" or "lastUpdate" node with the same method, I get an error, so this way must be wrong for those nodes which actually I can see they are differents.</p>

<p>I'm also trying to write output into a log file with no success, the most I get is an empty file.</p>

<p>Thank you for your time reading this.</p>

<p>It is because "description" and "lastUpdate" are not attributes but child nodes of the "situation" node.</p>

<p>Try:</p>

<pre><code>d = entry_situation[0].getElementsByTagName("description")[0]
print "Description: %s" % d.firstChild.nodeValue
</code></pre>

<p>You should use the same method to access the "situation" node from its parent "locality".</p>

<p>By the way you should take a look at the <a href="http://lxml.de/" rel="nofollow" title="lxml">lxml</a> module, especially the objectify API as yegorich said.  It is easier to use.</p>

python xml minidom