der*_*unk 10 python xml elementtree
用这个python 2.7.3(或2.7.0)代码我想改变属性"android:versionCode ='2'"的值,它具有名称空间前缀"android":
#!/usr/bin/python
from xml.etree.ElementTree import ElementTree, dump
import sys, os
# Problem here:
ElementTree.register_namespace("android", "http://schemas.android.com/apk/res/android")
tree = ElementTree()
tree.parse("AndroidManifest.xml")
root = tree.getroot()
root.attrib["{http://schemas.android.com/apk/res/android}versionCode"] = "3"
dump(tree)
Run Code Online (Sandbox Code Playgroud)
如果不使用注释"Problem here"的代码行,ElementTree会自动将http://schemas.android.com/apk/res/android的名称空间别名命名为"ns0"(导致"ns0:versionCode = '3'".
因此,我使用ElementTree.register_namespace将命名空间url映射到别名"android",这将在此处记录.
我尝试这样做时得到的错误是:
AttributeError: type object 'ElementTree' has no attribute 'register_namespace'
Run Code Online (Sandbox Code Playgroud)
谁知道为什么这不起作用?这个方法应该在python 2.7中可用.
ber*_*nie 24
register_namespace()是ElementTree 模块中包含的函数.
它不包含在ElementTree班级内......
旁白:由于这样做有时会导致混淆,因此通常不建议对模块和类使用相同的名称.但是我们现在不打算通过重命名广泛使用的模块来破坏生产代码吗?
您只需更改代码:
#!/usr/bin/python
import xml.etree.ElementTree as ET # import entire module; use alias for clarity
import sys, os
# note that this is the *module*'s `register_namespace()` function
ET.register_namespace("android", "http://schemas.android.com/apk/res/android")
tree = ET.ElementTree() # instantiate an object of *class* `ElementTree`
tree.parse("AndroidManifest.xml")
root = tree.getroot()
root.attrib["{http://schemas.android.com/apk/res/android}versionCode"] = "3"
ET.dump(tree) # we use the *module*'s `dump()` function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18285 次 |
| 最近记录: |