Iga*_*gal 10 python xml elementtree xmlroot
我有一个<root>
具有多个属性的XML 元素.我一直在使用这个ElementTree
包.
在我从xml文件中解析了一个树之后,我得到了文档根目录,但我希望得到所请求的属性,甚至是整个属性列表.
<root a="1" b="2" c="3">
</blablabla>
</root>
Run Code Online (Sandbox Code Playgroud)
如何<root>
使用ElementTree 检索元素的所有属性名称和值?
Mar*_*ers 24
每个Element
都有.attrib
一个字典属性; 只需使用它的映射方法来询问它的键或值:
for name, value in root.attrib.items():
print '{0}="{1}"'.format(name, value)
Run Code Online (Sandbox Code Playgroud)
要么
for name in root.attrib:
print '{0}="{1}"'.format(name, root.attrib[name])
Run Code Online (Sandbox Code Playgroud)
或使用.values()
或python上可用的任何其他方法dict
.
要获取单个属性,请使用标准订阅语法:
print root.attrib['a']
Run Code Online (Sandbox Code Playgroud)
attrib
ElementTree元素的属性(如返回的根getroot
)是一个字典.所以你可以这样做,例如:
from xml.etree import ElementTree
tree = ElementTree.parse('test.xml')
root = tree.getroot()
print root.attrib
Run Code Online (Sandbox Code Playgroud)
对于你的例子,它将输出
{'a': '1', 'b': '2', 'c': '3'}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23576 次 |
最近记录: |