· 8 years ago · Apr 19, 2018, 12:30 PM
1<MovieRating>
2 <Movie Id="1">
3 <Title>Father Figures</Title>
4 <Duration>01:53:00</Duration>
5 <Description>Upon learning that their mother has been lying to them for
6 years about their allegedly deceased father, two fraternal twin brothers
7 hit the road in order to find him.</Description>
8 <Release_Date>2017-12-22</Release_Date>
9 <Image_URL>https://image.com/1.jpg</Image_URL>
10 <Country>USA</Country>
11 <Genres>
12 <Genre Id="5">
13 <Title>Comedy</Title>
14 <Description>None</Description>
15 </Genre>
16 </Genres>
17 </Movies>
18 </MovieRating>
19
20import sqlite3
21import xml.sax
22
23class MoviesHandler(xml.sax.ContentHandler):
24 def __init__(self):
25 self.sql_attr_name = None
26 self.sql_attrs = dict()
27 self.conn = None
28
29 def startDocument(self):
30 self.conn = sqlite3.connect('moviez_sax.db')
31 c = self.conn.cursor()
32 c.execute('DROP TABLE IF EXISTS MOVIE')
33 c.execute('''
34 CREATE TABLE IF NOT EXISTS Movie (
35 Id INTEGER NOT NULL,
36 Title VARCHAR (1000) NOT NULL,
37 Duration TIME NOT NULL,
38 Description VARCHAR (5000),
39 Release_Date DATE NOT NULL,
40 Image_URL VARCHAR (1000),
41 Country VARCHAR (150),
42 PRIMARY KEY (Id)
43 );''');
44
45 def endDocument(self):
46 self.conn.commit()
47 self.conn.close()
48
49
50 def startElement(self, xml_name, xml_attrs):
51 #print("start element", xml_name)
52 if xml_name.lower() == 'movierating':
53 pass
54 if xml_name.lower() == 'movie':
55 self.sql_attr_name = None
56 self.sql_attrs = {
57 'Id' : '',
58 'Title' : '',
59 'Duration' : '',
60 'Description' : '',
61 'Release_Date' : '',
62 'Image_URL' : '',
63 'Country':''
64 }
65 self.sql_attrs['Id'] += xml_attrs['Id']
66 elif xml_name.lower() in ['id', 'title', 'duration', 'description' , 'release_date', 'image_url','country']:
67 self.sql_attr_name = xml_name
68 else:
69 pass
70
71 def characters(self, text):
72 if self.sql_attr_name is not None:
73 self.sql_attrs[self.sql_attr_name] += text
74
75 def endElement(self, xml_name):
76 if xml_name.lower() == 'movie':
77 c = self.conn.cursor()
78 c.execute('INSERT INTO MOVIE(Id,Title,Duration,
79 Description,Release_Date,Image_URL, Country) VALUES
80 (?,?,?,?,?,?,?)',
81 (self.sql_attrs['Id'].strip(),
82 self.sql_attrs['Title'].strip(),
83 self.sql_attrs['Duration'].strip(),
84 self.sql_attrs['Description'].strip(),
85 self.sql_attrs['Release_Date'].strip(),
86 self.sql_attrs['Image_URL'].strip(),
87 self.sql_attrs['Country'].strip()))
88
89if __name__ == '__main__':
90 parser = xml.sax.make_parser()
91 parser.setContentHandler(MovieRatingHandler())
92 parser.parse(open('movies.xml','r'))
93
94Father Figures n Comedy