iterparse是一个迭代解析器。它会发出
Element对象和事件,并在
Element解析时逐步构建整个树,因此最终它将在内存中存储整个树。
但是,有一个有限的内存行为很容易:在解析它们时删除不再需要的元素。
典型的“巨型xml”工作负载是单个根元素,带有大量代表记录的子元素。我认为这是您正在使用的XML结构吗?
通常,足以
clear()清空您正在处理的元素。您的内存使用量会增加一点,但不是很多。如果您的文件很大,那么即使是空
Element对象也将消耗过多的空间,在这种情况下,您还必须删除以前看到的
Element对象。请注意,您不能安全地删除当前元素。该
lxml.etree.iterparse文档描述了这种技术。
在这种情况下,您将在每次
</record>找到a时处理一条记录,然后删除所有先前的记录元素。
以下是使用无限长的XML文档的示例。它将在解析时打印该进程的内存使用情况。请注意,内存使用情况稳定并且不会继续增长。
from lxml import etreeimport resourceclass InfiniteXML (object): def __init__(self): self._root = True def read(self, len=None): if self._root: self._root=False return "<?xml version='1.0' encoding='US-ASCII'?><records>n" else: return """<record>nt<ancestor attribute="value">text value</ancestor>n</record>n"""def parse(fp): context = etree.iterparse(fp, events=('end',)) for action, elem in context: if elem.tag=='record': # processing goes here pass #memory usage print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # cleanup # first empty children from current element # This is not absolutely necessary if you are also deleting siblings, # but it will allow you to free memory earlier. elem.clear() # second, delete previous siblings (records) while elem.getprevious() is not None: del elem.getparent()[0] # make sure you have no references to Element objects outside the loopparse(InfiniteXML())


