2

I have a requirement where i need to parse the xml and need to capture the entire content into string. I tried using minidom and it was do-able. Pls help to achieve this by ElementTree

XML:

<?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"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

Minidom Example:

from xml.dom import minidom
xmldoc = minidom.parse(country.xml)
print xmldoc.toxml()

However when I'm doing it using it ElementTree not sure how this can be achieved: My code so far

 import xml.etree.ElementTree as etree
 tree = etree.parse('C:\\Users\\Administrator\\Desktop\\country.xml')
 print tree.getroot() *This is not working*
min2bro
  • 4,509
  • 5
  • 29
  • 55

1 Answers1

3

You can use etree.tostring() to produce a string from an ElementTree tree:

print etree.tostring(tree.getroot())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343