2016-04-04 63 views
-1

我有一個XML文件的結構如下:如何在Python中從XML文件中提取@value?

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

回答

1

假設根reffers到<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] 
+0

謝謝你,這是完美的作品:) – Python241820

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

其他解決方案,謝謝你,它的作品完美:) – Python241820