通过xml.dom.minidom解析

XML中的内容:




    
        modbus_ip
        127.0.0.1
        name的描述内容
    

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)