python xml.etree.ElementTree 模块批量处理xml 标签

在用 xml.etree.ElementTree 模块批量删除xml标签的时候,会出现的问题是,用遍历并不能一次将复合条件的标签删掉。

如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="lebian_Download_Error">下载失败,请检查网络</string>
    <string name="lebian_Download_Error_retry">下载出错,正在尝试重新下载,请稍候</string>
    <string name="lebian_MD5_mismatch">下载失败:MD5不匹配</string>
    <string name="lebian_MD5_of_original_file_mismatch">下载失败:原始文件MD5不匹配</string>
    <string name="lebian_apply_patch_failed">文件合并失败,请重试</string>
    <string name="lebian_authorities_error">以下Provider的authorities属性配置错误或缺失:</string>
    <string name="lebian_button_cancel">取消</string>
</resources>

在从网上看到有网友说,remove()每次删除标签的时候,都会重新获取对象。根据自己出现的情况于是找到了核实的方法:

就是将你删除的lebian标签个数统计出来,然后每删除一个标签,获取一下文件的对象。

步骤如下:

1:打开xml 文件获取root标签

2:将符合条件的标签进行删除

3:重新将删除后的xml写入文件。

4:一次遵循上面1-3的步骤,直到删除完毕

def main(filename,log):
    num=0
    try:
        tree=ET.parse(filename)
        root=tree.getroot()
        for i in root.getchildren():
            for chid in i.attrib:
                if i.attrib[chid].find("lebian")>=0 or i.attrib[chid].find("Lebian")>=0:
                    num=num+1
                    break;
    except Exception,e:
        print e
    finally:
        return num
def remove(num,filename,log):
    time=0;
    while(time<num):
        tree=ET.parse(filename)
        root=tree.getroot()
        for i in root.getchildren():
            for chid in i.attrib:
                if i.attrib[chid].find("lebian")>=0 or i.attrib[chid].find("Lebian")>=0:
                    time=time+1
                    root.remove(i)
                    break;
        tree.write(filename,encoding="utf-8",xml_declaration=True)


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值