xml 节点属性的删除

xml 节点属性的删除
我想要用python读取这个xml,并且把公共档案的 xmlns:xsi、xmlns、xsi:schemaLocation 这些属性全给删除了,只保留节点名称
[](


```xml
 <公共档案 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema" xmlns:行政事业单位="http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema" xsi:schemaLocation="http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema 公共档案.xsd"> 



with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:

for lin in f1:

print(lin)

if old_str in lin:

lin = lin.replace(old_str, new_str)

f2.write(lin)

通过字符串替换的方式最快

使用lxml 运用xpath语法选择属性,可以参考这个
http://t.csdn.cn/ZQfKV

你的需求直接 用正则替换就可以实现吧,参考这个:

关于该问题,我找了一篇非常好的博客,你可以看看是否有帮助,链接:详解XML节点属性排序

属性都删完了
直接拼一个xml串更简单吧

可以看我之前写得笔记,如果不想用正则去删除,可以先转换成字典: