从ElementTree获取属性名称和值 [英] Get attribute names and values from ElementTree

查看:693
本文介绍了从ElementTree获取属性名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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

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

推荐答案

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

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)

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

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

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

要获取单个属性,请使用标准的< a href = http://docs.python.org/2/reference/expressions.html#subscriptions rel = noreferrer>订阅语法:

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

print root.attrib['a']

这篇关于从ElementTree获取属性名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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