<p>下面的代码遍历xml并填充dict,其中键是设备id,值是dict列表。每个dict表示一个“field”属性。只收集定义为“有趣”的字段。你知道吗</p>
<pre><code>import xml.etree.ElementTree as ET
import pprint
xml = '''<server host="WeatherGoose" address="10.0.0.11" tempunit="F">
<devices>
<device id="0114BE53110000E6" name="WeatherGoose" type="WxGoos" available="1" index="0">
<field key="TempC" value="20.55" niceName="Temperature (C)" min="-20" max="50" type="2"/>
<field key="TempF" value="68.99" niceName="Temperature (F)" min="-4" max="122" type="2"/>
<field key="Humidity" value="42.00" niceName="Relative Humidity" min="0" max="99" type="2"/>
<field key="Airflow" value="33.27" niceName="Air Flow" min="0" max="100" type="2"/>
<field key="Light" value="2.00" niceName="Light Level" min="1" max="99" type="2"/>
<field key="Sound" value="30.00" niceName="Sound Level" min="0" max="99" type="2"/>
<field key="IO1" value="99.00" niceName="Moisture" min="0" max="99" type="2"/>
<field key="IO2" value="99.00" niceName="IO-2" min="0" max="99" type="2"/>
<field key="IO3" value="0.00" niceName="Door Contacts" min="0" max="99" type="2"/>
</device>
</devices>
</server>
'''
root = ET.fromstring(xml)
result = {}
interesting_fields = ['Airflow','TempF']
devices = root.findall('.//devices/device')
for device in devices:
result[device.attrib['id']] = [f.attrib for f in device.findall('./field') if f.attrib['key'] in interesting_fields]
pprint.pprint(result)
</code></pre>
<p>输出</p>
<pre><code>{'0114BE53110000E6': [{'key': 'TempF',
'max': '122',
'min': '-4',
'niceName': 'Temperature (F)',
'type': '2',
'value': '68.99'},
{'key': 'Airflow',
'max': '100',
'min': '0',
'niceName': 'Air Flow',
'type': '2',
'value': '33.27'}]}
</code></pre>