0

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 list.

My attempt:

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)
#for item in lst:
#    print('Country: ', item.get('name'))

Thanks in advance.

martineau
  • 112,593
  • 23
  • 157
  • 280
Viraj Kaulkar
  • 271
  • 1
  • 2
  • 14

1 Answers1

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'))
tdelaney
  • 63,514
  • 5
  • 71
  • 101