【发布时间】: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>
由此我希望能够打印出<time> 元素的from 和to 属性以及其子节点value 中的value 属性<temperature>
如果我运行下面的 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 在循环中显示
<class 'untangle.Element'>