Python创建、修改、保存XML文件——xml.etree.ElementTree模块

https://gemini-yang.blog.csdn.net/article/details/106219001?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2-106219001-blog-130799948.235%5Ev38%5Epc_relevant_anti_t3_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2-106219001-blog-130799948.235%5Ev38%5Epc_relevant_anti_t3_base

 

from xml.etree import ElementTree
import xml.etree.ElementTree as ET
class CommentedTreeBuilder(ElementTree.TreeBuilder):
    def __init__(self, *args, **kwargs):
        super(CommentedTreeBuilder, self).__init__(*args, **kwargs)

    def comment(self, data):
        self.start(ElementTree.Comment, {})
        self.data(data)
        self.end(ElementTree.Comment)


def read_xml(in_path):
    # 读取文件,并带有注释
    parser = ET.XMLParser(target=CommentedTreeBuilder())
    tree = ElementTree.parse(in_path, parser=parser)

    root = tree.getroot()
    root.find('transports').find('transport').find('property').set('value',"./conf/t2sdk_77.ini"  )
    tree = ET.ElementTree(root)
    return tree

if __name__ == '__main__':
    path = r'C:/Users/DELL/Desktop/20000/ufx-mid-stock-adapter.xml'
    tree = read_xml(path)
    # encoding='UTF-8', xml_declaration=True,表示encoding='UTF-8',其他标签前缀不变
    tree.write("C:/Users/DELL/Desktop/20000/ufx-mid-stock-adapter.xml", encoding='UTF-8', xml_declaration=True)

 

# encoding:utf-8
import os
import xml.etree.ElementTree as ET

nowDir = os.getcwd()  # 得到进程当前工作目录
fileList = os.listdir(nowDir)  # 得到进程当前工作目录中的所有文件名称列表
for fileName in fileList:  # 获取文件列表中的文件
    if fileName.endswith("xml"):
        print fileName
        tree = ET.parse(fileName)
        root = tree.getroot()

        for shuink in shuinkList:
            for child in root:
                for sub in child:
                    if sub.tag == "width" or sub.tag == "height":
                        sub.text = str(int(sub.text)/shuink)
                    for subchild in sub:
                        if subchild.tag == "xmin" or subchild.tag == "xmax" or subchild.tag == "ymin" or subchild.tag == "ymax":
                            subchild.text = str(int(subchild.text) / shuink)
            tree.write( fileName)  # 保存修改后的XML文件
for property in root.iter('property'):
    print(property.attrib)
    if property.attrib["name"]=="UFX_CFG":
        print(1123)
        break

 

posted @ 2023-06-21 20:01  liuweipaul123  阅读(268)  评论(0编辑  收藏  举报