2013-01-14 190 views
8

我有一個具有多個屬性的XML <root>元素。我一直在使用ElementTree包。從ElementTree獲取屬性名稱和值

在我從一個xml文件中解析了一棵樹之後,我得到了文檔根目錄,但我想獲取請求的屬性,甚至是整個屬性列表。

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

我怎樣才能檢索到的所有屬性名稱和值與ElementTree的一個<root>元素?

回答

13

每個Element有一個屬性.attrib這是一個字典;簡單地使用它mapping methods要求它爲它的鍵或值:

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

爲了得到一個單獨的屬性,使用標準subscription syntax

print root.attrib['a'] 
4

一個ElementTree的元素的屬性attrib(如由getroot返回的根)是字典。所以,你可以做,例如:

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

將輸出,爲你的榜樣

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

一些不錯的循環中,您可以使用它會得到的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