Python 2.7:类型对象“ ElementTree”没有属性“ register_namespace”; [英] Python 2.7: type object "ElementTree" has no attribute "register_namespace"

查看:178
本文介绍了Python 2.7:类型对象“ ElementTree”没有属性“ register_namespace”;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此python 2.7.3(或2.7.0)代码,我想更改属性 android:versionCode ='2'的值,该属性的名称空间前缀为 android:

with this python 2.7.3 (or 2.7.0) code I want to change the value of the attribute "android:versionCode='2'", which has the namespace prefix "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)

当不使用带有此处有问题注释的代码行时,ElementTree将自动命名http://schemas.android.com/apk/res/android 转换为 ns0(结果为 ns0:versionCode ='3'。

When not using the line of code commented with "Problem here", ElementTree is auto-naming the namespace alias for http://schemas.android.com/apk/res/android to "ns0" (resulting in "ns0:versionCode='3'".

因此我正在使用ElementTree.register_namespace进行映射命名空间网址为别名 android,在此处

Thus I'm using ElementTree.register_namespace to map the namespace url to the alias name "android", which is documented here.

尝试执行此操作时遇到的错误是:

The error I get when I try to do this is:

AttributeError: type object 'ElementTree' has no attribute 'register_namespace'

任何人都知道为什么这不行吗?此方法应该在python 2.7中可用。

Anybody knows why this is not working? This method should be available in python 2.7.

推荐答案

register_namespace()是ElementTree 模块中包含的函数

它不是包含在 ElementTree 类中...

register_namespace() is a function contained within the ElementTree module.
It is not contained within the ElementTree class...

另外:由于有时会引起混淆,因此通常不建议对模块和类使用相同的名称。但是我们现在不打算通过重命名广泛使用的模块来破坏生产代码吗?

An aside: Because of the confusion that is sometimes caused by doing so it is generally not recommended to use the same name for both module and class. But we are not about to break production code by renaming a widely used module now are we?

您只需要更改代码:

#!/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

这篇关于Python 2.7:类型对象“ ElementTree”没有属性“ register_namespace”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆