重复使用python查询XML
-
22-09-2019 - |
题
我有我需要在运行查询一些XML文档。我已经创造了一些Python脚本(使用ElementTree的)要做到这一点,因为我依稀熟悉使用它。
它的工作方式是我用不同的参数运行脚本几次,这取决于我想了解一下。
这些文件可以是比较大的(+ 10MB)等需要花费相当长的时间来分析它们。在我的系统,只需运行:
tree = ElementTree.parse(document)
花费大约30秒,随后有的findall查询只增加围绕第二了这一点。
看到作为我这样做的方式要求我反复解析文件,我想知道是否有某种缓存机制,我可以使用,以便ElementTree.parse计算可以在随后的查询中减少的。
我认识了聪明的事情,在这里做可能会尝试和一批为许多查询作为python脚本可能在一起,但我希望有可能是另一种方式。
感谢。
解决方案
当我第二次的建议,使用lxml的,您可以通过使用内置cElementTree获得巨大的性能提升。
from xml.etree import cElementTree as ElementTree
其他提示
首先,考虑使用lxml
的ElementTree
执行:结果
http://lxml.de/
这是libxml2的一个包装,我发现表现良好。
运行Python交互,使对同一对象etree多个查询。 ipython
是增强的交互式Python解释与容易获得内省和便利性的语法。
E.g。交互检查 note.xml 与IPython的使用lxml.etree
。
$ ipython
Python 2.5.1 (r251:54863, Jul 10 2008, 17:24:48)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: from lxml import etree
In [2]: doc = etree.parse(open("note.xml"))
In [3]: etree.dump(doc.getroot())
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
In [4]: doc.xpath('/note/*')
Out[4]:
[<Element to at 89cf02c>,
<Element from at 89cf054>,
<Element heading at 89cf07c>,
<Element body at 89cf0a4>]
不隶属于 StackOverflow