码迷,mamicode.com
首页 > 其他好文 > 详细

解析XML

时间:2018-08-30 18:17:25      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:set   get   解析xml   .data   element   tree   imp   脚本   turn   

通过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)

解析XML

标签:set   get   解析xml   .data   element   tree   imp   脚本   turn   

原文地址:http://blog.51cto.com/feature09/2166928

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!