XPath가 빠릅니다. 당신의 XPath의 수는 하나의 호출을 줄일 수
doc = etree.fromstring(xml)
btags = doc.xpath('//a/b')
for b in btags:
print b.text
를 그만큼 빨리하지 않으면, 당신은 Liza Daly's fast_iter을 시도 할 수 있습니다. 이렇게하면 전체 XML을 먼저 etree.fromstring
으로 처리 할 필요가 없으며 하위 노드를 방문한 후에 상위 노드가 버려집니다. 이 두 가지 모두 메모리 요구 사항을 줄이는 데 도움이됩니다. 아래는 더 이상 필요하지 않은 다른 요소를 제거하는 데 더 적극적인 a modified version of fast_iter
입니다. 너무 당신에게 유용 읽기 증명할 수 큰 XML 파일을 구문 분석에
def fast_iter(context, func, *args, **kwargs):
"""
fast_iter is useful if you need to free memory while iterating through a
very large XML file.
http://lxml.de/parsing.html#modifying-the-tree
Based on Liza Daly's fast_iter
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
See also http://effbot.org/zone/element-iterparse.htm
"""
for event, elem in context:
func(elem, *args, **kwargs)
# It's safe to call clear() here because no descendants will be
# accessed
elem.clear()
# Also eliminate now-empty references from the root node to elem
for ancestor in elem.xpath('ancestor-or-self::*'):
while ancestor.getprevious() is not None:
del ancestor.getparent()[0]
del context
def process_element(elt):
print(elt.text)
context=etree.iterparse(io.BytesIO(xml), events=('end',), tag='b')
fast_iter(context, process_element)
Liza Daly's article. 기사에 따르면, fast_iter
의 lxml은 cElementTree
의 iterparse
보다 빠를 수 있습니다. (표 1 참조). 이 모든 메모리를 저장하지 않는
가
import lxml.etree as ET
for event, elem in ET.iterparse(filelike_object):
if elem.tag == "a":
process_a(elem)
for child in elem:
process_child(child)
elem.clear() # destroy all child elements
elif elem.tag != "b":
elem.clear()
참고,하지만 난이 기술을 사용하여 기가 이상의 XML 스트림을 통해 웨이드 할 수있었습니다 :
매우 유용합니다. –