2014-05-19 4 views
1

J'utilise etree et lxml,Comment obtenir un tag particulier d'un document XML en python

Je suis en mesure d'obtenir le texte du nœud à l'aide du XPath, mais je veux tout le contenu y compris les balises

<?xml version="1.0"?> 
<data> 
    <country name="Liechtenstein"> 
     <rank>1</rank> 
     <year>2008</year> 
     <gdppc>141100</gdppc> 
     <neighbor name="Austria" direction="E"/> 
     <neighbor name="Switzerland" direction="W"/> First Country 
    </country> 
    <country name="Singapore"> 
     <rank>4</rank> 
     <year>2011</year> 
     <gdppc>59900</gdppc> 
     <neighbor name="Malaysia" direction="N"/> Second Country 
    </country> 
    <country name="Panama"> 
     <rank>68</rank> 
     <year>2011</year> 
     <gdppc>13600</gdppc> 
     <neighbor name="Costa Rica" direction="W"/> 
     <neighbor name="Colombia" direction="E"/> Third Country 
    </country> 
</data> 

Si je donne le pays, je veux que le texte soit retourné comme

<country name="Panama"> 
      <rank>68</rank> 
      <year>2011</year> 
      <gdppc>13600</gdppc> 
      <neighbor name="Costa Rica" direction="W"/> 
      <neighbor name="Colombia" direction="E"/> First Country 
</country> 

code je utilise est en ce moment

import xml.etree.ElementTree as ET 
tree = ET.parse('country_data.xml') 
root = tree.getroot() 
for i in tree.findall('.//country'): 
    print i.text 
+1

Veuillez également inclure (la partie pertinente du) code Python que vous avez jusqu'à présent. – Tomalak

+0

@Tomalak J'ai ajouté le code maintenant –

Répondre

2

Cela fonctionnerait-il pour vous?

for i in tree.findall('.//country'): 
    print ET.tostring(i) 
+0

Merci cela a fonctionné. –

Questions connexes