经常会用到操作xml格式文件,不得不说python代码写起来特别丝滑,只需要简单几行代码就可以搞定,话不多说先看xml格式xml.png

import xml.etree.ElementTree as ET


def read_xml(file):
    """
    读取并解析xml
    :param file:
    :return:
    """
    return ET.parse(file)


def write_xml(tree, out_path):
    """将xml文件写出
       tree: xml树
       out_path: 写出路径"""
    tree.write(out_path, encoding="utf-8", xml_declaration=True)
    return True

也可以根据修改节点xml属性值和节点值


def make_xml(xml_path, wxml_path, values):
    """
    修改cnf 文件
    如: LogType=1;BlackFlag=1
    :param values: tag=value;tag=value
    """
    # 读取待修改文件
    tree = ET.parse(xml_path)
    root = tree.getroot()

    for value in values.split(';'):
        if ' ' in value:
            for ta in root.iter(value.split(' ')[0]):
                map_list = value.split(' ')[1].split('=')
                if map_list[0] in ta.attrib:
                    ta.attrib[map_list[0]] = map_list[1]
        else:
            list = value.split('=')
            for ta in root.iter(list[0]):
                ta.text = list[1]
    return write_xml(tree, wxml_path)

怎么样比Java写起来是不是感觉很简洁

Last modification:September 4th, 2020 at 02:46 pm
如果觉得我的文章对你有用,请随意赞赏