2011-12-20 17 views
19

Ho una stringa contenente dati XML restituita da una richiesta http.Python ElementTree: analisi di una stringa e acquisizione dell'istanza ElementTree

Sto utilizzando ElementTree per analizzare i dati e desidero quindi cercare ricorsivamente un elemento.

Secondo this question, posso cercare solo in modo ricorsivo con result.findall() se result è di tipo ElementTree piuttosto che digito Element.

Ora xml.etree.ElementTree.fromstring(), utilizzato per analizzare la stringa, restituisce un oggetto Element, mentre xml.etree.ElementTree.parse(), usato per analizzare un file, restituisce un oggetto ElementTree.

La mia domanda è quindi: Come posso analizzare la stringa e ottenere un'istanza ElementTree? (senza alcuna follia come scrivere un file temporaneo)

risposta

25

Quando si utilizza ElementTree.fromstring() quello che stai ricevendo indietro è fondamentalmente la radice dell'albero, quindi se si crea un nuovo albero come questo ElementTree.ElementTree(root) si otterrà te' sto cercando.

Così, per renderlo più chiaro:

from xml.etree import ElementTree 
tree = ElementTree.ElementTree(ElementTree.fromstring(<your_xml_string>)) 

o:

from xml.etree.ElementTree import fromstring, ElementTree 
tree = ElementTree(fromstring(<your_xml_string>)) 
+0

voglio solo aggiungi - per chi usa lxml - che in lxml (dove un elemento appartiene sempre a un documento/albero, anche se implicito), puoi usare il metodo getrootttree(). – Steven

+0

Grazie! Design API davvero fastidioso in etree, per avere diversi tipi di output solo in base alla sorgente di input. Davvero confuso :( –

+0

Questo non è molto chiaro nella documentazione. "Fromstring() analizza l'XML da una stringa direttamente in un Elemento, che è l'elemento principale dell'albero analizzato.Altre funzioni di analisi possono creare un ElementTree." – Snorfalorpagus

6

Trasforma il tuo stringa in un oggetto simile a file e utilizzare ElementTree.parse:

from xml.etree import ElementTree 
from cStringIO import StringIO 

tree = ElementTree.parse(StringIO(string)) 
+0

Ottimo, questo è quello che stavo cercando. :-) –

Problemi correlati