-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple_data_handler.py
More file actions
88 lines (72 loc) · 2.33 KB
/
simple_data_handler.py
File metadata and controls
88 lines (72 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import xml.sax.handler
import xml.sax
import sys
import os
class ArrayItem(list):
"""
Provides a common interface to add items to list
"""
def add_item(self, item):
self.append(item)
class DictItem(dict):
"""
Provides a commong interface to add items to dict
"""
def add_key(self, key):
self.key = key
def add_item(self, item):
self[self.key] = item
def null(input):
return input
class SimpleDataHandler(object, xml.sax.handler.ContentHandler):
"""
SAX Handler capable of parsing iTunes Libarary XML files.
After parsing, the final item is accessible through the final_item
attribute.
"""
# XXX: Don't do any conversions now. <key>123</key>
# doesn't provide any type information, so converting
# primitive types, like integers, produces inconsistent
# results
# Mapping of type -> conversion function
types = {
'string' : null, # Not happy with unicode
'date' : null, # Could use strftime...
'integer' : null # Convert to int
}
def __init__(self):
self.content = []
self.stack = []
@property
def state_info(self):
return "Stack: %s Current_item: %s" % (self.stack, self.current_item)
def startElement(self, name, attrs):
to_add = None
if name == 'dict':
to_add = DictItem()
elif name == 'array':
to_add = ArrayItem()
if to_add is not None:
self.stack.append(to_add)
def endElement(self, name):
if 'key' == name:
current_key = ''.join(self.content).strip()
#self.content = []
self.current_item.add_key(current_key)
elif name in self.types:
f = self.types[name]
item = f(''.join(self.content).strip())
#self.content = []
self.current_item.add_item(item)
elif name == 'dict' or name == 'array':
finished = self.stack.pop(-1)
if self.current_item is not None:
self.current_item.add_item(finished)
else:
self.final_item = finished
self.content=[]
def characters(self, content):
self.content.append(content)
@property
def current_item(self):
return self.stack[-1] if len(self.stack) > 0 else None