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.

2
  • 1
    Viraj Kaulkar: Not sure if it would be good enough, but lst = tree.findall('country') seems to work. Commented Oct 5, 2016 at 18:24
  • print(data) gives me string back. And triple single quotes are used to write a multi-line string in python 3. Commented Oct 5, 2016 at 18:24

1 Answer 1

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'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.