如何在Python中从XML文件中提取@value?

2024-10-01 15:35:53 发布

您现在位置: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”中提取:

^{pr2}$

Tags: 文件nameidcityvalueunitxmlcurrent
3条回答

假设根引用到<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]
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"))

我就这么做

import xml.etree.ElementTree as ET
root = ET.parse('path_to_your_xml_file')
temperature = root.find('.//temperature')

现在温度属性是一本包含所有信息的字典

^{pr2}$

相关问题 更多 >

    热门问题