繁体   English   中英

如何使用Python和ElementTree挖掘XML文件中的字段数据

[英]How do I dig out field data in the XML file using Python and ElementTree

我正在尝试使用Python和ElementTree模块从Weathergoose设备读取XML数据。 我可以从“设备”节点获取“名称”数据,但我想读取“设备”节点下列出的数据。 我特别希望具有“ TempF”的值

这是XML数据的示例:

<server host="WeatherGoose" address="10.0.0.11" <omited stuff> 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>

这是我到目前为止的内容:

import os
import urllib
import xml.etree.ElementTree as ET

def main():
  feed = urllib.urlopen("http://10.0.0.11/data.xml")

  try:
    tree = ET.parse(feed)    
    root = tree.getroot()    
    event = root.find("devices")

    for e in event:
      print e.attrib['name']

  except Exception, inst:
    print "Error: %s: %s" % (tree, inst)

if __name__ == "__main__":
  main()

这产生了设备的主机名,但是我找不到找到“现场密钥”数据的魔力。 任何帮助,将不胜感激。

您应该能够通过使用xpath field[@key='TempF'] (当前元素上下文为device )来选择具有值为TempFkey属性的field元素。

示例(将feed更改回您的urllib调用)...

def main():
    feed = "test.xml"  # Used an external file for testing.

    try:
        tree = ET.parse(feed)
        root = tree.getroot()
        devices = root.findall("devices/device")

        for device in devices:
            print device.get("name")
            print device.find("field[@key='TempF']").get("value")

    except Exception, inst:
        print "Error: %s" % inst

这将打印:

WeatherGoose
68.99

注意:如果您有多个device元素,则会在每个元素上进行迭代。

下面的代码遍历xml并填充一个dict,其中键是设备ID,值是字典列表。 每个字典代表一个“字段”属性。 仅收集定义为“有趣”的字段。

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)

输出

{'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'}]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM