使用Python反复查询XML
我有一些XML文档需要查询。我用Python写了一些脚本(使用ElementTree库)来处理这些文档,因为我对它有一点了解。
这个过程是这样的:我根据想要查找的信息,使用不同的参数多次运行这些脚本。
这些文件可能比较大(超过10MB),所以解析它们需要花费不少时间。在我的系统上,仅仅运行:
tree = ElementTree.parse(document)
大约需要30秒,而后续的查找查询只会多花大约一秒钟。
因为我现在的做法需要重复解析文件,我在想有没有什么缓存机制可以使用,这样在后续查询时可以减少ElementTree.parse的计算时间。
我意识到聪明的做法可能是尽量把多个查询一起处理在Python脚本中,但我希望能找到其他的方法。
谢谢。
3 个回答
1
首先,建议你使用 lxml
这个库来实现 ElementTree
:
http://lxml.de/
这个库是对 libxml2 的一个封装,我觉得它的表现很好。
你可以在 Python 中进行交互式操作,针对同一个 etree 对象进行多次查询。 ipython
是一个增强版的交互式 Python 解释器,使用起来更方便,能更容易地查看和使用各种功能。
例如,你可以用 ipython 交互式地查看 note.xml 文件,使用 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>]
3
我同意使用lxml这个建议,不过如果你用内置的cElementTree的话,性能会有很大的提升。
from xml.etree import cElementTree as ElementTree