import os
import xml.dom.minidom
def replace_xml_tag_content(AnnoPath, tag_name, old_content, new_content):
try:
Annolist = os.listdir(AnnoPath)
for annotation in Annolist:
xml_file = os.path.join(AnnoPath,annotation)
dom = xml.dom.minidom.parse(xml_file) # 使用 minidom 解析 XML 文件
collection = dom.documentElement # 获取根元素
objectlist = collection.getElementsByTagName(tag_name) # 获取指定标签名的元素列表
for ob in objectlist:
if ob.firstChild.data == old_content: # 如果元素的文本内容与指定的旧内容相同
ob.firstChild.data = new_content # 替换为新内容
with open(xml_file, 'w', encoding='utf-8') as f:
dom.writexml(f, addindent='', newl='', encoding='utf-8') # 写回到原文件
print(f"成功替换 {tag_name} 中的 {old_content} 为 {new_content}")
except Exception as e:
print(f"替换过程中出现异常:{e}")
if __name__ == '__main__':
# 调用函数进行替换
AnnoPath = 'annoPath/' # 替换为你的 XML 文件路径
tag_name_to_replace = 'name' #不用改
old_content_to_replace = 'old_name' #需要被替换的name
new_content = 'new_name' #新的name
replace_xml_tag_content(AnnoPath, tag_name_to_replace, old_content_to_replace, new_content)
改变xml的标签名
最新推荐文章于 2024-05-31 14:29:45 发布