How would you read an XML file using sax and convert it to a lxml etree.iterparse element?
To provide an overview of the problem, I have built an XML ingestion tool using lxml for an XML feed that will range in the size of 25 - 500MB that needs ingestion on a bi-daily basis, but needs to perform a one time ingestion of a file that is 60 - 100GB's.
I had chosen to use lxml based on the specifications that detailed a node would not exceed 4 -8 GB's in size which I thought would allow the node to be read into memory and cleared when finished.
An overview if the code is below
elements = etree.iterparse(
self._source, events = ('end',)
)
for event, element in elements:
finished = True
if element.tag == 'Artist-Types':
self.artist_types(element)
def artist_types(self, element):
"""
Imports artist types
:param list element: etree.Element
:returns boolean:
"""
self._log.info("Importing Artist types")
count = 0
for child in element:
failed = False
fields = self._getElementFields(child, (
('id', 'Id'),
('type_code', 'Type-Code'),
('created_date', 'Created-Date')
))
if self._type is IMPORT_INC and has_artist_type(fields['id']):
if update_artist_type(fields['id'], fields['type_code']):
count = count + 1
else:
failed = True
else:
if create_artist_type(fields['type_code'],
fields['created_date'], fields['id']):
count = count + 1
else:
failed = True
if failed:
self._log.error("Failed to import artist type %s %s" %
(fields['id'], fields['type_code'])
)
self._log.info("Imported %d Artist Types Records" % count)
self._artist_type_count = count
self._cleanup(element)
del element
Let me know if I can add any type of clarification.
iterparse
does not read the entire file into memory. It builds a tree, but incrementally. Just delete nodes after you are finished processing them usingclear()
– Lodestone