Given this xml file, please help me complete the following: This XML document co
ID: 664785 • Letter: G
Question
Given this xml file, please help me complete the following:
This XML document contains records for CDs. The root element is CATALOG and contains a series of CD elements, each of which has a number of child elements such as TITLE, PRICE and so on.
Write a program that will read the file and print out the following information with an appropriate message:
The total number of CDs in the file and the total price of purchasing one of each.
The minimum, maximum, and average price for the CDs in the file.
The total number of CDs released in the year 1990.
Print the names of all artists who are from America (USA).
Use list comprehensions to minimize the code required in parts a – d.
Should be in python, with appropriately named variables and using list comprehensions to minimize the code.
Link to the xml file:
https://drive.google.com/file/d/0B5FX84Uyz9fjOGhHQl9RdHFuVlU/view
Explanation / Answer
#Reading catalog.xml using python code
import xml.sax
class MovieHandler( xml.sax.ContentHandler ): #defining class
def __init__(self):
self.Title = "" #declaring initial variables with default value " "
self.Artist = ""
self.Country = ""
self.Company = ""
self.Price= ""
self.Year = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "CD": #if tag CD found
print ('*****CD*****') #print it
title = attributes["CD"]
print ("Title:", CD) #print as title
# Call when an elements ends
def endElement(self, tag): #calling each element of tag
if self.CurrentData == "Title": #if title found and so on conditions
print ("Title:", self.Title)
elif self.CurrentData == "Artist":
print ("Artist:", self.format)
elif self.CurrentData == "Country":
print ("Country:", self.Country)
elif self.CurrentData == "Company":
print ("Company:", self.rating)
elif self.CurrentData == "Price":
print ("Price:", self.Price)
elif self.CurrentData == "Year":
print ("Year:", self.Year)
self.CurrentData = ""
# Call when a character is read
def characters(self, content):
if self.CurrentData == "Title":
self.type = content
elif self.CurrentData == "Artist":
self.format = content
elif self.CurrentData == "Country":
self.year = content
elif self.CurrentData == "Company":
self.rating = content
elif self.CurrentData == "Price":
self.stars = content
elif self.CurrentData == "Year":
self.description = content
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = MovieHandler()
parser.setContentHandler( Handler )
parser.parse("catalog.xml") #sending XML file name as argument
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.