【问题标题】:How to fix Xpath Operators problem in python xml parsing如何修复 python xml 解析中的 Xpath Operators 问题
【发布时间】:2019-11-22 17:51:20
【问题描述】:

我正在尝试查找 maxtemp 大于 0 的日期。但是,以下代码给了我一个空列表。

我尝试在 w3schools xpath 示例中使用一个示例,它可以找到价格超过 35 的书籍的标题。

示例: /书店/书[价格>35]/书名

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>

这是我正在尝试使用的代码和 xml 文件:

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)

这是 XML 文件:

<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>

我只想要列表中的一项。

【问题讨论】:

标签: xml python-3.x xpath xml-parsing


【解决方案1】:

这可以使用 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)

输出:

1.9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多