Savvis
Savvis

Reputation: 53

python parse conditional xml value

Here is my XML file:

<METAR>
<wind_dir_degrees>210</wind_dir_degrees>
<wind_speed_kt>14</wind_speed_kt>
<wind_gust_kt>22</wind_gust_kt>
</METAR>

Here is my script to parse the wind direction and speed. However, the wind gust is a conditional value and doesn't always appear in my xml file. I'd like to show the value if it does exist and nothing if it doesn't.

import xml.etree.ElementTree as ET
from urllib import urlopen

link = urlopen('xml file')

tree = ET.parse(link)
root = tree.getroot()

data = root.findall('data/METAR')
for metar in data:
    print metar.find('wind_dir').text

I tried something like this but get errors

data = root.findall('wind_gust_kt')
for metar in data:
        if metar.find((wind_gust_kt') > 0:
           print "Wind Gust: ", metar.find('wind_gust_kt').text

Upvotes: 0

Views: 937

Answers (2)

Warren Weckesser
Warren Weckesser

Reputation: 114946

When you loop over the result of the findall function, there is no need to call find again--you already have the element.

You can simplify your code to something like this:

tree = ET.parse(link)
for wind_gust in tree.findall('wind_gust_kt'):
    print "Wind gust:", wind_gust.text

You might have been following this tutorial:

http://docs.python.org/library/xml.etree.elementtree.html#tutorial

In the example there, the find method of the loop variable is called in order to find child elements of the loop element. In your case, the wind_gust variable is the element that you want, and it has no child elements.

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142226

You can use findtext with a default value of '', eg:

print "Wind Gust: ", meta.findtext('wind_gust_kt', '')

Upvotes: 1

Related Questions