2013-01-14 20 views
8

Ho un elemento XML <root> con diversi attributi. Sto usando il pacchetto ElementTree.Ottieni i nomi e i valori degli attributi da ElementTree

Dopo aver analizzato un albero da un file xml, ottengo la radice del documento, ma voglio ottenere l'attributo richiesto, o anche l'intero elenco di attributi.

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

Come faccio a recuperare tutti i nomi degli attributi e dei valori per un elemento <root> con ElementTree?

risposta

13

Ogni Element ha un attributo .attrib che è un dizionario; è sufficiente utilizzare è mapping methods chiedere che per esso è chiavi o valori:

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

o

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

o utilizzare .values() o uno qualsiasi degli altri metodi disponibili su un pitone dict.

Per ottenere un singolo attributo, utilizzare lo standard subscription syntax:

print root.attrib['a'] 
4

L'attributo attrib di un elemento ElementTree (come la radice restituita da getroot) è un dizionario. Così si può fare, per esempio:

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

che sarà in uscita, per il tuo esempio

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

Qualche bel ciclo si può utilizzare otterrà per ogni elemento della xmlObject è etichetta, testo e attributi funzionerà per 2 livelli XML, non è il modo migliore per iterare ma può essere utile per cose semplici ...

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 
Problemi correlati