如何用python操作XML文件

备注: 基于python3

背景:在统计覆盖率的时候希望绕属性name为test的节点

具体实现源码如下所示,基本都是基于节点属性操作的,当然也就可以基于tag等其他标签去做,可根据需要调整

from xml.etree.ElementTree import ElementTree, Element


class XML_DEMO():
    def __init__(self, in_path, out_path):
        self.in_path = in_path
        self.out_path = out_path
        self.tree = None
        self.parent_nodes = []

    def read_xml(self):
        # 读取XML文件
        self.tree = ElementTree()
        self.tree.parse(self.in_path)

    def write_xml(self):
        # 将处理后的xml写入XML文件
        self.tree.write(self.out_path, encoding="utf-8", xml_declaration=True)

    def if_match_attrib(self, node, attrib_map):
        for k, v in attrib_map.items():
            if node.attrib.get(k) and node.attrib.get(k) == v:
                return True
        return False

    def find_nodes_by_path(self, path):
        return self.tree.findall(path)

    def get_node_by_attrib(self, nodelist, attrib_map):
        result_nodes = []
        for node in nodelist:
            if self.if_match_attrib(node, attrib_map):
                result_nodes.append(node)
        return result_nodes

    @staticmethod
    def change_node_attrib(nodelist, attrib_map):
        for node in nodelist:
            for k, v in attrib_map.items():
                node.attrib[k] = v

    @staticmethod
    def change_node_text(nodelist, text, is_add=False, is_delete=False):
        for node in nodelist:
            if is_add:
                node.text += text
            elif is_delete:
                node.text = ""
            else:
                node.text = text

    @staticmethod
    def create_node(tag, property_map, content):
        element = Element(tag, property_map)
        element.text = content
        return element

    @staticmethod
    def add_child_node(nodelist, element):
        for node in nodelist:
            node.append(element)

    @staticmethod
    def del_node_by_attrib(nodelist, kv_map):
        for parent_node in nodelist:
            children = parent_node.getchildren()
            for child in children:
                for k, v in kv_map.items():
                    if child.attrib.get(k) and child.attrib.get(k).find(v) >= 0:
                        parent_node.remove(child)


if __name__ == "__main__":
    # 初始化xml类对象,指定源文件和目标文件
    xd = XML_DEMO("sec.xml", "des.xml")
    xd.read_xml()
    # 需要删除的节点的父节点
    del_parent_nodes = xd.find_nodes_by_path("packages/package/")
    # 删除父节点下属性name为test的节点
    xd.del_node_by_attrib(del_parent_nodes, {"name": "test"})
    # 将删除后节点后的xml写入目标文件
    xd.write_xml()
原文地址:https://www.cnblogs.com/smileyes/p/9582754.html