我在XML文件中有以下结构:
<current>
<city id="2510170" name="Triana">
<coord lon="-6.02" lat="37.38"/>
<country>ES</country>
<sun rise="2016-04-04T06:04:05" set="2016-04-04T18:50:07"/>
</city>
<temperature value="290.92" min="288.15" max="296.15" unit="kelvin"/>
<humidity value="93" unit="%"/>
<pressure value="1009" unit="hPa"/>
<wind>
<speed value="8.2" name="Fresh Breeze"/>
<gusts/>
<direction value="230" code="SW" name="Southwest"/>
</wind>
<clouds value="90" name="overcast clouds"/>
<visibility/>
<precipitation mode="no"/>
<weather number="501" value="moderate rain" icon="10d"/>
<lastupdate value="2016-04-04T10:05:00"/>
</current>
问题是如何使用Python的XPATH提取温度(@value)?也就是说,提取自&#34; 290.2&#34;以下一行:
<temperature value="290.92" min="288.15" max="296.15" unit="kelvin"/>
答案 0 :(得分:1)
假设root引用<current>
节点
from lxml import etree
xml_file = 'test.xml'
with open(xml_file) as xml:
root = etree.XML(xml.read())
temperature_value = root.xpath('./temperature/@value')[0]
答案 1 :(得分:1)
我只想做
import xml.etree.ElementTree as ET
root = ET.parse('path_to_your_xml_file')
temperature = root.find('.//temperature')
现在,temperature.attrib是一个包含所有信息的字典
print temperature.attrib['value'] # 290.92
print temperature.attrib['min'] # 288.15
print temperature.attrib['max'] # 296.15
print temperature.attrib['unit'] # kelvin
答案 2 :(得分:0)
from xml.etree import cElementTree as ET
tree = ET.parse("test.xml")
root = tree.getroot()
for temp in root.findall('temperature'):
print(temp.get("value"))