Skip to content Skip to sidebar Skip to footer

Parse XML With Using ElementTree Library

I am trying to parse an xml data to print its content with ElementTree library in python 3. but when I print lst it returns me an empty list. Error: Returning an empty array of li

Solution 1:

Tree references the root item <data> already so it shouldn't be in your path statement. Just find "country".

import xml.etree.ElementTree as ET
data = '''
    <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>
    </data>'''

tree = ET.fromstring(data)
lst = tree.findall('data/country')
print(lst)

# check position in tree
print(tree.tag)
print(tree.findall('country'))

Post a Comment for "Parse XML With Using ElementTree Library"