-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathxml2sql.py
More file actions
144 lines (110 loc) · 3.71 KB
/
xml2sql.py
File metadata and controls
144 lines (110 loc) · 3.71 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
xml2sql.py
Kailash Nadh, http://nadh.in
October 2011
License: MIT License
Documentation: http://nadh.in/code/xmlutils.py
"""
import codecs
import xml.etree.ElementTree as et
class xml2sql:
def __init__(self, input_file, output_file, encoding='utf-8'):
"""Initialize the class with the paths to the input xml file
and the output sql file
Keyword arguments:
input_file -- input xml filename
output_file -- output sql filename
encoding -- character encoding
"""
self.output_buffer = []
self.sql_insert = None
self.output = None
self.num_insert = 0
# open the xml file for iteration
self.context = et.iterparse(input_file, events=("start", "end"))
# output file handle
try:
self.output = codecs.open(output_file, "w", encoding=encoding)
except:
print("Failed to open the output file")
raise
def convert(self, tag="item", table="table", ignore=[], limit=-1, packet=8):
"""Convert the XML file to SQL file
Keyword arguments:
tag -- the record tag. eg: item
table -- table name
ignore -- list of tags to ignore
limit -- maximum number of records to process
packet -- maximum size of an insert query in MB (MySQL's max_allowed_packet)
Returns:
{ num: number of records converted,
num_insert: number of sql insert statements generated
}
"""
self.context = iter(self.context)
# get to the root
try:
# for py version 2.x
event, root = self.context.next()
except AttributeError:
# for py version 3.x
event, root = next(self.context)
items = []
fields = []
field_name = ''
tagged = False
started = False
sql_len = 0
n = 0
packet_size = 0
max_packet = 1048576 * packet
# iterate through the xml
for event, elem in self.context:
# if elem is an unignored child node of the record tag, it should be written to buffer
should_write = elem.tag != tag and started and elem.tag not in ignore
# and other fields that haven't been created
should_tag = not tagged and should_write
if event == 'start':
if elem.tag == tag and not started:
started = True
elif should_tag:
# if elem is nested inside a "parent", field name becomes parent_elem
field_name = '_'.join((field_name, elem.tag)) if field_name else elem.tag
else:
if should_write:
if should_tag:
fields.append(field_name) # add field name to csv header
# remove current tag from the tag name chain
field_name = field_name.rpartition('_' + elem.tag)[0]
if elem.text is None or elem.text.strip() == '':
items.append('-')
else:
items.append(elem.text.replace('"', r'\"').replace('\n', r'\n').replace('\'', r"\'"))
# end of traversing the record tag
elif elem.tag == tag and len(items) > 0:
tagged = True
if self.sql_insert is None:
self.sql_insert = 'INSERT INTO ' + table + ' (' + ','.join(fields) + ')\n'
sql = r'("' + r'", "'.join(items) + r'")'
sql_len += len(sql)
if sql_len + len(self.sql_insert) + 100 < max_packet:
# store the sql statement in the buffer
self.output_buffer.append(sql)
else:
# packet size exceeded. flush the sql and start a new insert query
self._write_buffer()
self.output_buffer.append(sql)
sql_len = 0
items = []
n += 1
# halt if the specified limit has been hit
if n == limit:
break
elem.clear() # discard element and recover memory
self._write_buffer() # write rest of the buffer to file
return {"num": n, "num_insert": self.num_insert}
def _write_buffer(self):
"""Write records from buffer to the output file"""
self.output.write(self.sql_insert + 'VALUES\n' + ', \n'.join(self.output_buffer) + ';\n\n')
self.output_buffer = []
self.num_insert += 1