Python 2.7: type object “ElementTree” has no attribute “register_namespace”

后端 未结 1 676
逝去的感伤
逝去的感伤 2020-12-08 17:06

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\":



        
相关标签:
1条回答
  • 2020-12-08 17:36

    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
    
    0 讨论(0)
提交回复
热议问题