python - 在 Python 中生成非常大的 XML 文件?

标签 python xml lxml

有谁知道在 Python 中生成非常大的 xml 文件(例如 100-500 MiB)的内存高效方法?

我一直在使用 lxml,但内存使用量已达到顶峰。

最佳答案

也许您可以使用模板引擎而不是自己生成/构建 xml?

Genshi例如基于 xml 并支持流式输出。一个非常基本的例子:

from genshi.template import MarkupTemplate

tpl_xml = '''
<doc xmlns:py="http://genshi.edgewall.org/">
<p py:for="i in data">${i}</p>
</doc>
'''

tpl = MarkupTemplate(tpl_xml)
stream = tpl.generate(data=xrange(10000000))

with open('output.xml', 'w') as f:
    stream.render(out=f)

这可能需要一段时间,但内存使用率仍然很低。

Mako 的相同示例模板引擎(不是“本地”xml),但速度更快:

from mako.template import Template
from mako.runtime import Context

tpl_xml = '''
<doc>
% for i in data:
<p>${i}</p>
% endfor
</doc>
'''

tpl = Template(tpl_xml)

with open('output.xml', 'w') as f:
    ctx = Context(f, data=xrange(10000000))
    tpl.render_context(ctx)

最后一个示例在我的笔记本电脑上运行了大约 20 秒,生成了一个(诚然非常简单)151 MB 的 xml 文件,完全没有内存问题。 (根据 Windows 任务管理器,它一直保持在 10MB 左右)

根据您的需要,这可能是一种比使用 SAX 等更友好、更快速的生成 xml 的方法...查看文档以了解您可以使用这些引擎做什么(还有其他引擎,我刚刚挑选出来这两个作为例子)

关于python - 在 Python 中生成非常大的 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3049188/

相关文章:

java - 使用 Dom 进行解析会产生类型不匹配

php - 我的 PHP 应用程序需要导出为一系列不同的 XML 格式 : should I use XSLT or native PHP?

xml - 使用Xpath从当前XML文档中的链接文件中获取内容

python - Python 的 VS 代码中的 "Debug Adapter Executable not provide"

python - 根据相同的值但不同的键名称连接两个 Python 字典(如 SQL 的 JOIN)

python - 更改 lxml 中的元素命名空间

python - 控制搜索深度 findall Lxml

python - 如何在python中查找元素树中元素的数量?

python - z3 (py) smt-lib2 输出

python - db.TextProperty() 上的 "BadValueError: Property xxxx is not multi-line"