import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for i in tree.findall('.//rank'):
print ET.tostring(i)
Here I want to get all the rank elements ( with maintaining its absolute structure )
I am getting the output as
<rank>1</rank>
<rank>4</rank>
<rank>68</rank>
What should I do to get the output as
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
</country>
<country name="Singapore">
<rank>4</rank>
</country>
<country name="Panama">
<rank>68</rank>
</country>
</data>
when the input xml file country_data.xml is
<?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>