python xml.etree.Element 在处理 xml文件时写入产生ns0

疑难杂症   ns0   python xml 修改属性  

例如

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
     <application android:allowBackup="false" android:icon="@drawable/app_icon" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">  
    </application>
</manifest>  

处理脚本

# -*- coding:UTF-8 -*-  
try:  
    import xml.etree.cElementTree as ET
except ImportError:  
    import xml.etree.ElementTree as ET

tree = ET.ElementTree(file="22601.xml")  
root = tree.getroot()  
for ele in tree.iter(tag="application"):  
    print ele.attrib
    ele.attrib['android:name']="x.x.x.x.x"

tree.write("22601.xml",encoding="utf-8",xml_declaration=True)

处理后的xml

<manifest xmlns:ns0="http://schemas.ns0.com/apk/res/ns0"  
     <application ns0:allowBackup="false" ns0:icon="@drawable/app_icon" ns0:label="@string/app_name"
android:name = "x.x.x.x.x"  
ns0:theme="@ns0:style/Theme.NoTitleBar.Fullscreen">  
    </application>
</manifest>  

解决办法

  • 在ElementTree之前,需要注册register_namespace否则会出现ns0
ET.register_namespace('android', "http://schemas.android.com/apk/res/android")