[英]How can I extract xml value @ attribute = something from python
[英]how to extract an @value from XML file in Python?
我在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)? 即,從以下行的“ 290.2”中提取:
<temperature value="290.92" min="288.15" max="296.15" unit="kelvin"/>
假設根引用到<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]
我只會做
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
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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.