Viraj Kaulkar
Viraj Kaulkar

Reputation: 321

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

Upvotes: 0

Views: 70

Answers (1)

tdelaney
tdelaney

Reputation: 77407

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'))

Upvotes: 1

Related Questions