簡體   English   中英

通過python獲取xml中元素的值

[英]Obtain element's value in xml via python

如何獲得具有實體和值的元素內的值?

元素在“級別”內以下是示例xml:

<observations>

<station wmo-id="94576" bom-id="040913" tz="Australia/Brisbane" stn- 
name="BRISBANE" stn-height="8.13" type="AWS" lat="-27.4808" lon="153.0389" 
forecast-district-id="QLD_PW015" description="Brisbane">

<period index="0" time-utc="2018-03-29T05:50:00+00:00" time-local="2018-03-                    
29T15:50:00+10:00" wind-src="OMD">

<level index="0" type="surface">
<element units="Celsius" type="apparent_temp">29.0</element>
<element units="Celsius" type="delta_t">2.1</element>
<element units="km/h" type="gust_kmh">11</element>
<element units="knots" type="wind_gust_spd">6</element>
<element units="Celsius" type="air_temperature">25.4</element>
<element start-time-local="2018-03-29T09:00:00+10:00" end-time-local="2018- 
03-29T15:51:00+10:00" duration="411" start-time-utc="2018-03- 
28T23:00:00+00:00" end-time-utc="2018-03-29T05:51:00+00:00" units="mm" 
type="rainfall">0.8</element>
</level>
</period>
</station>
</observations>

我已經嘗試過使用for循環,它最多可以返回結果

for station in root[1]:
  stnname = station.attrib['stn-name']
  for perioddata in station:
    index = perioddata.attrib['index']
    for leveldata in perioddata:
        typedata = leveldata.attrib['type']
        for elementdata in leveldata:
            value = elementdata.attrib['type']
            print(value)
            #result shows only type but not type's value
            #the result i want is apparent_temp & 29.0

鑒於此元素:

<element units="Celsius" type="apparent_temp">29.0</element>

unitstype是元素的屬性 ,但是29.0是元素的文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM