Python 从 ElementTree 获取属性名称和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14323335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:05:06  来源:igfitidea点击:

Get attribute names and values from ElementTree

pythonxmlelementtreexmlroot

提问by Igal

I have an XML <root>element with several attributes. I've been using the ElementTreepackage.

我有一个<root>具有多个属性的 XML元素。我一直在使用这个ElementTree包。

After I've parsed a tree from an xml file, I'm getting the document root, but I want to get the requested attribute, or even the entire list of attributes.

从 xml 文件解析树后,我获得了文档根目录,但我想获得请求的属性,甚至是整个属性列表。

<root a="1" b="2" c="3">
    </blablabla>
</root>

How can I retrieve all attribute names and values for a <root>element with ElementTree?

如何<root>使用 ElementTree检索元素的所有属性名称和值?

采纳答案by Martijn Pieters

Each Elementhas an attribute .attribthat is a dictionary; simply use it's mapping methodsto ask it for it's keys or values:

每个Element都有一个.attrib作为字典的属性;只需使用它的映射方法来询问它的键或值:

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.

或使用.values()python 上可用的或任何其他方法dict

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

要获取单个属性,请使用标准订阅语法

print root.attrib['a']

回答by intuited

The attribattribute of an ElementTree element (like the root returned by getroot) is a dictionary. So you can do, for example:

attribElementTree 元素的属性(如 返回的根getroot)是一个字典。所以你可以这样做,例如:

from xml.etree import ElementTree
tree = ElementTree.parse('test.xml')
root = tree.getroot()
print root.attrib

which will output, for your example

对于您的示例,它将输出

{'a': '1', 'b': '2', 'c': '3'}

回答by Kobi K

Some nice loop you can use it will get for each element of the xmlObject it's tag, text and attribute it will work for 2 levels XML, it's not the best way to iterate but it can be useful for simple things...

您可以使用的一些不错的循环将为 xmlObject 的每个元素获取它的标记、文本和属性,它将适用于 2 级 XML,这不是迭代的最佳方式,但它对简单的事情很有用...

for headTag in xmlObject.getchildren():
    print headTag.tag, headTag.text, headTag.attrib
    for bodyTag in headTag.getchildren():
        print "\t", bodyTag.tag, bodyTag.text, bodyTag.attrib