Ad

I Do Not Succeed In Python To Print The Movie Titles From XML File

- 1 answer

I am trying to get python print all the movie names in the XML file but i can't figure it out. I am pretty new to Python can somebody put me in the right direction?

My code so far:

import xml.etree.ElementTree as ET
tree = ET.parse('text.xml')
root = tree.getroot()

for elem in root:
    print(elem.find('movie').get('title'))

The XML file:

<collection>
    <genre category="Action">
        <decade years="1980s">
            <movie favorite="True" title="Indiana Jones: The raiders of the lost Ark">
                <format multiple="No">DVD</format>
                <year>1981</year>
                <rating>PG</rating>
                <description>
                'Archaeologist and adventurer Indiana Jones
                is hired by the U.S. government to find the Ark of the
                Covenant before the Nazis.'
                </description>
            </movie>
               <movie favorite="True" title="THE KARATE KID">
               <format multiple="Yes">DVD,Online</format>
               <year>1984</year>
               <rating>PG</rating>
               <description>None provided.</description>
            </movie>
            <movie favorite="False" title="Back 2 the Future">
               <format multiple="False">Blu-ray</format>
               <year>1985</year>
               <rating>PG</rating>
               <description>Marty McFly</description>
            </movie>
        </decade>
     </genre>
 </collection>
Ad

Answer

import xml.etree.ElementTree as ET
tree = ET.parse('text.xml')
root = tree.getroot()

for movie in root.iter('movie'):
    print(movie.get('title'))

Output:

Indiana Jones: The raiders of the lost Ark
THE KARATE KID
Back 2 the Future

You can take a look at xml.etree.ElementTree here

Ad
source: stackoverflow.com
Ad