改变xml的标签名

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)

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值