【问题标题】:Parsing XML with Python - Accessing Values使用 Python 解析 XML - 访问值
【发布时间】:2019-02-03 21:14:30
【问题描述】:

我最近有一个 RaspberryPi 并开始学习 Python。首先,我想解析一个 XML 文件,我正在通过 untangle 库执行此操作。

我的 XML 看起来像:

<?xml version="1.0" encoding="utf-8"?>
<weatherdata>
  <location>
    <name>Katherine</name>
    <type>Administrative division</type>
    <country>Australia</country>
    <timezone id="Australia/Darwin" utcoffsetMinutes="570" />
    <location altitude="176" latitude="-14.65012" longitude="132.17414" geobase="geonames" geobaseid="7839404" />
  </location>
  <sun rise="2019-02-04T06:33:52" set="2019-02-04T19:16:15" />
  <forecast>
    <tabular>
      <time from="2019-02-04T06:30:00" to="2019-02-04T12:30:00" period="1">
        <!-- Valid from 2019-02-04T06:30:00 to 2019-02-04T12:30:00 -->
        <symbol number="9" numberEx="9" name="Rain" var="09" />
        <precipitation value="1.8" />
        <!-- Valid at 2019-02-04T06:30:00 -->
        <windDirection deg="314.8" code="NW" name="Northwest" />
        <windSpeed mps="3.3" name="Light breeze" />
        <temperature unit="celsius" value="26" />
        <pressure unit="hPa" value="1005.0" />
      </time>
      <time from="2019-02-04T12:30:00" to="2019-02-04T18:30:00" period="2">
        <!-- Valid from 2019-02-04T12:30:00 to 2019-02-04T18:30:00 -->
        <symbol number="9" numberEx="9" name="Rain" var="09" />
        <precipitation value="2.3" />
        <!-- Valid at 2019-02-04T12:30:00 -->
        <windDirection deg="253.3" code="WSW" name="West-southwest" />
        <windSpeed mps="3.0" name="Light breeze" />
        <temperature unit="celsius" value="29" />
        <pressure unit="hPa" value="1005.0" />
      </time>
    </tabular>
  </forecast>
</weatherdata>

由此我希望能够打印出&lt;time&gt; 元素的fromto 属性以及其子节点value 中的value 属性&lt;temperature&gt;

如果我运行下面的 Python 脚本,我可以正确打印出温度值:

for forecast in data.weatherdata.forecast.tabular.time:
  print (forecast.temperature['value'])

但是如果我跑了

for forecast in data.weatherdata.forecast.tabular:
  print ("time is " + forecast.time['from'] + "and temperature  is " + forecast.time.temperature['value'])

我收到一个错误:

print (forecast.time['from'] + forecast.time.temperature['value'])
TypeError: list indices must be integers, not str

谁能告诉我如何正确访问这些值?

【问题讨论】:

  • 显示print(type(forecast))的输出
  • @stovfl 在循环中显示&lt;class 'untangle.Element'&gt;

标签: python xml parsing


【解决方案1】:

forecast.time 应该是一个列表,因为它确实有多个值,每个 &lt;time&gt; 节点一个。

您是否希望 forecast.time['from'] 自动汇总这些数据?

【讨论】:

  • 啊,好的,谢谢,所以print ("time is " + forecast.time[0]['from']) 给了我第一个值。所以在Python中我如何遍历所有例如forecast.time[*i*]['from']?
  • for forecast in data.weatherdata.forecast.tabular.time: print (forecast['from'], forecast.temperature['value'])
  • 呃,抱歉,来晚了:)
猜你喜欢
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 2019-11-07
  • 2013-04-13
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多