import os
import xml.etree.ElementTree as ET
def changesku(inputpath):
listdir = os.listdir(inputpath)
for file in listdir:
if file.endswith('xml'):
file = os.path.join(inputpath,file)
tree = ET.parse(file)
root = tree.getroot()
for object1 in root.findall('object'): #我要修改的元素在object里面,所以需要先找到object
for sku in object1.findall('name'): #查找想要修改的所有同种元素
if (sku.text == '005'): #‘005’为原始的text
sku.text = '008' #修改‘name’的标签值
tree.write(file,encoding='utf-8') #写进原始的xml文件,不然修改就无效,‘encoding = “utf - 8”’避免原始xml #中文字符乱码
else:
pass
else:
pass
if __name__ == '__main__':
inputpath = 'D:\\easy\\hebing_xml' #这是xml文件的文件夹的绝对地址
changesku(inputpath)

本文介绍了一种使用Python批量修改特定目录下所有XML文件中指定元素值的方法。通过解析XML文件并遍历查找需要修改的元素,可以将这些元素的文本内容从'005'替换为'008'。

被折叠的 条评论
为什么被折叠?



