0
votes

I'm trying to find the days where the maxtemp is greater than 0. However,the following code gives me a empty list.

I tried using an example on w3schools xpath exmaples where it finds the tittle of books that are priced over 35.

Example: /bookstore/book[price>35]/title

xml:

<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

This is the code and xml file I'm trying to work with:

import xml.etree.ElementTree as ET 
tree = ET.parse('SaintJohn.xml')
root = tree.getroot()
list=root.findall('.//stationdata[maxtemp>0]/maxtemp')
for i in list:
    print(i.text)

This is the XML file:

<climate>
<stationdata day="1" month="1" year="2019">
<maxtemp description="Maximum Temperature" 
units="°C">1.9</maxtemp><mintemp description="Minimum Temperature" 
units="°C">-10.6</mintemp><meantemp description="Mean Temperature" 
units="°C">-4.4</meantemp><heatdegdays description="Heating Degree 
Days" units="°C">22.4</heatdegdays>
</stationdata>
<stationdata day="2" month="1" year="2019"><maxtemp 
description="Maximum Temperature" units="°C">-10.6</maxtemp> 
<mintemp description="Minimum Temperature" 
units="°C">-22.4</mintemp><meantemp description="Mean Temperature" 
units="°C">-16.5</meantemp><heatdegdays description="Heating 
Degree Days" units="°C">34.5</heatdegdays></stationdata>
</climate>

I would like just one item in the list.

1

1 Answers

0
votes

This can be done using lxml:

temp = [your xml above]

from lxml import html
root = html.fromstring(temp)

list = root.xpath('.//stationdata/maxtemp[text()>0]')
for i in list:
    print(i.text)

Output:

1.9