簡體   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