使用python lxml.etree获取巨大的XML文件

时间:2012-08-07 16:34:26

标签: python lxml

我想在Python中使用lxml.etree解析一个巨大的xml(> 200MB)。我尝试使用etree.parse加载XML文件,但由于文件大小,这不起作用:

etree.parse('file.xml')Traceback (most recent call last):
File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 2706, in lxml.etree.parse (src/lxml/lxml.etree.c:49958)
  File "parser.pxi", line 1500, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:71797)
  File "parser.pxi", line 1529, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:72080)
  File "parser.pxi", line 1429, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:71175)
  File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:68173)
  File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:64257)
  File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:65178)
  File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64521)
lxml.etree.XMLSyntaxError: Excessive depth in document: 256 use XML_PARSE_HUGE option, line 1276, column 7

由于我想使用xpath表达式,我必须先解析文件。我如何解析XML文件?如何将XML_PARSE_HUGE用于lxml.etree

谢谢!

1 个答案:

答案 0 :(得分:22)

尝试创建自定义XMLParser实例:

from lxml.etree import XMLParser, parse
p = XMLParser(huge_tree=True)
tree = parse('file.xml', parser=p)