Apr-25-2019, 06:23 AM
import xml.etree.ElementTree as ET import csv def xml_parser(file): xml = ET.parse(file) genres = xml.findall('genre') for genre in genres: #print(genre.attrib) for decade in genre: #print(decade.attrib) for movie in decade: #print(movie.attrib) fmt = movie.find('format') year = movie.find('year') rate = movie.find('rating') #print(fmt.text, year.text, rate.text) #print(fmt.attrib, year.attrib, rate.attrib) yield genre.get('category'), decade.get('years'), movie.get('title'), fmt.text, year.text, rate.text return xmlIt's a generator. You have to consume it with your writer. For example you can use the method
writerows()
on the csv_writer instance. I put some print statements in the nested for loops. If you put the code without the function on module level, you can try in the repel. Methods of ElementTree you need to know: attrib, name, text, get(), findall()
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!