如何从Python中获取XML文件的更新?

时间:2016-09-04 07:46:22

标签: python xml notifications

我是Python的新手。我在服务器中有一个XML文件,它将由设备定期更新,如下所示。

<notifications
    xmlns="http://XXXXX">
    <notification>
        <received>2016-09-04T13:48:57Z</received>
        <source-address>x.x.x.x</source-address>
        <notification-type>type-1</notification-type>
        <message>message-1</message>
    </notification>
    <notification>
        <received>2016-09-04T13:49:21Z</received>
        <source-address>X.X.X.X</source-address>
        <notification-type>type-2</notification-type>
        <message>message-2</message>
    </notification>
    <notification>
        <received>2016-09-04T13:52:38Z</received>
        <source-address>X.X.X.X</source-address>
        <notification-type>type-3</notification-type>
        <message>message-3</message>
    </notification>
    <notification>
        <received>2016-09-04T14:01:21Z</received>
        <source-address>X.X.X.X</source-address>
        <notification-type>type-4</notification-type>
        <message>message-4</message>
    </notification>
    <notification>
        <received>2016-09-04T14:01:51Z</received>
        <source-address>X.X.X.X</source-address>
        <notification-type>type-5</notification-type>
        <message>message-5</message>
    </notification>
</notifications>

我有兴趣在设备发布通知时获取<notification-type> and <message>的值。有没有办法在Python中做到这一点?

1 个答案:

答案 0 :(得分:0)

两个独立的问题 - 第一个问题是监控文件的变化......这看起来已经解决了

第二是用Python读取XML文件

import xml.etree.ElementTree as Et

def process(notification):

    received          = notification[0].text
    print (received)

    notification_type = notification[2].text
    print (notification_type)


xml = Et.ElementTree()
xml.parse('notifications.xml')
root = xml.getroot()

for notification in root:
    process(notification)