Get attribute names and values from ElementTree

后端 未结 3 1892
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 05:28

I have an XML element with several attributes. I\'ve been using the ElementTree package.

After I\'ve parsed a tree from an xml fil

3条回答
  •  被撕碎了的回忆
    2021-02-08 06:21

    Each Element has an attribute .attrib that is a dictionary; simply use it's mapping methods to ask it for it's keys or values:

    for name, value in root.attrib.items():
        print '{0}="{1}"'.format(name, value)
    

    or

    for name in root.attrib:
        print '{0}="{1}"'.format(name, root.attrib[name])
    

    or use .values() or any of the other methods available on a python dict.

    To get an individual attribute, use the standard subscription syntax:

    print root.attrib['a']
    

提交回复
热议问题