python 将xml文件格式化处理

import os

from lxml import etree

'''
将不规范的xml文件 规范化
'''

path = r"~/path"
for dirs, root, filenames in os.walk(path):
for filename in filenames:
path_file = os.path.join(path, dirs, filename)

if not str(path_file).endswith(".xml"):
continue

# 读取XML文件
tree = etree.parse(path_file)

# 将XML文件重新格式化
xml_string = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
with open(path_file, 'wb') as f:
f.write(xml_string)
posted @ 2023-09-02 12:42  Lyxin_c  阅读(425)  评论(0编辑  收藏  举报