Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

xml - Python 2.7: type object "ElementTree" has no attribute "register_namespace"

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)

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'".

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'

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

You simply need to change your code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...