0

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

2 Answers 2

1

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

print "Wind Gust: ", meta.findtext('wind_gust_kt', '')
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.