xml.etree.ElementTree对xml文件的基本处理操作

xml.etree.ElementTree对xml文件的基本处理操作

文章目录

  • xml.etree.ElementTree对xml文件的基本处理操作
      • 初始XML文件
      • 处理要求
      • 源代码:
      • 处理后xml


初始XML文件


<framework>
        <processers>
                <processer name="AProcesser" file="lib64/A.so"
                        path="/tmp">
                processer>
                <processer name="BProcesser" file="lib64/B.so" value="fordelete">
                processer>
                <processer name="BProcesser" file="lib64/B.so2222222"/>

                <services>
                        <service name="search" prefix="/bin/search?"
                                output_formatter="OutPutFormatter:service_inc">

                                <chain sequency="chain1"/>
                                <chain sequency="chain2">chain>
                        service>
                        <service name="update" prefix="/bin/update?">
                                <chain sequency="chain3" value="fordelete"/>
                        service>
                services>
        processers>
framework>

处理要求

此处demo主要涉及两点:
1、添加新节点;
2、xml 的结构美化处理:xml节点树的美化处理,主要涉及节点间的换行及不同级节点间的空格,xml.etree.ElementTree没有开发相关的接口直接对xml类型的文件进行美化处理,需要参照pretty_xml函数处理

源代码:

#!/usr/bin/python
# -*- coding=utf-8 -*-

from xml.etree.ElementTree import ElementTree,Element

def read_xml(in_path):
    '''读取并解析xml文件
       in_path: xml路径
       return: ElementTree'''
    tree = ElementTree()
    tree.parse(in_path)
    return tree

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

def if_match(node, kv_map):
    '''判断某个节点是否包含所有传入参数属性
       node: 节点
       kv_map: 属性及属性值组成的map'''
    for key in kv_map:
        if node.get(key) != kv_map.get(key):
            return False
    return True

#---------------search -----

def find_nodes(tree, path):
    '''查找某个路径匹配的所有节点
       tree: xml树
       path: 节点路径'''
    return tree.findall(path)


def get_node_by_keyvalue(nodelist, kv_map):
    '''根据属性及属性值定位符合的节点,返回节点
       nodelist: 节点列表
       kv_map: 匹配属性及属性值map'''
    result_nodes = []
    for node in nodelist:
        if if_match(node, kv_map):
            result_nodes.append(node)
    return result_nodes

#---------------change -----

def change_node_properties(nodelist, kv_map, is_delete=False):
    '''修改/增加 /删除 节点的属性及属性值
       nodelist: 节点列表
       kv_map:属性及属性值map'''
    for node in nodelist:
        for key in kv_map:
            if is_delete:
                if key in node.attrib:
                    del node.attrib[key]
            else:
                node.set(key, kv_map.get(key))

def change_node_text(nodelist, text, is_add=False, is_delete=False):
    '''改变/增加/删除一个节点的文本
       nodelist:节点列表
       text : 更新后的文本'''
    for node in nodelist:
        if is_add:
            node.text += text
        elif is_delete:
            node.text = ""
        else:
            node.text = text

def create_node(tag, property_map, content):
    '''新造一个节点
       tag:节点标签
       property_map:属性及属性值map
       content: 节点闭合标签里的文本内容
       return 新节点'''
    element = Element(tag, property_map)
    element.text = content
    return element

def add_child_node(nodelist, element):
    '''给一个节点添加子节点
       nodelist: 节点列表
       element: 子节点'''
    for node in nodelist:
        node.append(element)

def del_node_by_tagkeyvalue(nodelist, tag, kv_map):
    '''同过属性及属性值定位一个节点,并删除之
       nodelist: 父节点列表
       tag:子节点标签
       kv_map: 属性及属性值列表'''
    for parent_node in nodelist:
        children = parent_node.getchildren()
        for child in children:
            if child.tag == tag and if_match(child, kv_map):
                parent_node.remove(child)

def pretty_xml(tree,indent,newline,level=0):
    '''Pretty Xml File before writing
       :param tree: 创建好的父节点,未初始化的tree
       :param indent: 缩进“\t”
       :param newline: 换行“\n”
       :param level: 用于递归操作的变量,实现不同级别节点增加不同数量的缩进“\t”'''
    treeList=list(tree)
    for subElement in treeList:
        # print(subElement)
        if treeList.index(subElement) < (len(treeList) - 1):
            subElement.tail=newline+indent*(level+1)
        else:
            subElement.tail=newline+indent*level
            pretty_xml(subElement,indent,newline,level+1)

if __name__ == "__main__":

    #1. 读取xml文件
    tree = read_xml("./demo.xml")
    root = tree.getroot()
    new_node = create_node("NEW_NODE",{"Attribute1":"true","Attribute2":"..."},'context:123123123...')
    root.append(new_node)
    pretty_xml(root, '\t', '\n')
    write_xml(tree,'demo_out.xml')

处理后xml

demo_out.xml:


<framework>
        <processers>
                <processer file="lib64/A.so" name="AProcesser" path="/tmp">
                processer>
                <processer file="lib64/B.so" name="BProcesser" value="fordelete">
                processer>
                <processer file="lib64/B.so2222222" name="BProcesser" />
                <services>
                        <service name="search" output_formatter="OutPutFormatter:service_inc" prefix="/bin/search?">
                                <chain sequency="chain1" />
                                <chain sequency="chain2" />
                        service>
                        <service name="update" prefix="/bin/update?">
                                <chain sequency="chain3" value="fordelete" />
                        service>
                services>
        processers>
        <NEW_NODE Attribute1="true" Attribute2="...">context:123123123...NEW_NODE>
framework>

你可能感兴趣的:(xml,python,开发语言)