如何用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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM