【问题标题】:Obtain element's value in xml via python通过python获取xml中元素的值
【发布时间】:2018-03-31 03:30:51
【问题描述】:

如何获取具有实体和值的元素内的值?

元素在“级别”内 以下是示例 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

【问题讨论】:

标签: python xml for-loop


【解决方案1】:

给定这个元素:

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

units 和type 是元素的属性,而29.0 是元素的文本。

【讨论】:

  • 那么如何获取元素文本呢?我使用 elementdata.attrib['type'] 返回“明显的 _temp”,但我怎样才能获得元素文本?
  • elementdata.text
  • 我试过 elementdata.text['apparent_temp'] 和 elementdata.text['type'] 。我得到 TypeError: string indices must be integers, not str
  • 只有elementdata.text 自己。
  • 谢谢,现在我可以获取数据了,但是,如果我只想获取属性“gust_kmh”文本,我该怎么做呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2018-04-12
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
相关资源
最近更新 更多