解析XML

通過xml.dom.minidom解析

XML中的內容:

<?xml version="1.0" encoding="UTF-8" ?>

<configuration>
    <property>
        <name>modbus_ip</name>
        <value>127.0.0.1</value>
        <describe>name的描述內容</describe>
    </property>
</configuration>

Python3 腳本內容:

import xml.dom.minidom as xminidom
from os.path import dirname, abspath

# 解析XML文件,獲取相應數據
def introduce_args(input_name):
    """
    :param input_name: string
    :return: string
    """
    setting_path = dirname(dirname(abspath(__file__))) + '/conf/setting.xml'
    dom_tree = xminidom.parse(setting_path)
    collection = dom_tree.documentElement

    properties = collection.getElementsByTagName("property")  # 找到標籤是property的

    for message in properties:
        name = message.getElementsByTagName('name')[0]  # 在標籤是property的裏面找標籤是name的
        if name.childNodes[0].data == input_name:
            value = message.getElementsByTagName('value')[0]
            return value.childNodes[0].data

if __name__ == '__main__':
    v  = introduce_args("modbus_ip")  # 輸入想要查詢的name,獲取value
    print(v)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章