如何在Python中使用Xpath? [英] How to use Xpath in Python?
本文介绍了如何在Python中使用Xpath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
libxml2 有很多优点:
- 符合 spec
- 积极发展和社区参与
- 速度。这实际上是一个C实现的python包装。
- Ubiquity。 libxml2库是无处不在的,因此经过良好的测试。
下降包括:
- 符合规格。这是严格的在其他库中,像默认名称空间处理一样容易。
- 使用本机代码。这可能会因为您的应用程序的分发/部署而变得痛苦。 RPM可用于缓解一些这种痛苦。
- 手动资源处理。在下面的示例中注意对freeDoc()和xpathFreeContext()的调用。这不是非常Pythonic。
如果你做简单的路径选择,请坚持使用 ElementTree (它包含在Python 2.5中)。如果您需要完整的规范兼容性或原始速度,并且可以应对本地代码的分发,请使用libxml2。
libxml2 XPath的示例使用
import libxml2
doc = libxml2.parseFile (tst.xml)
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval(// *)
如果len(res)!= 2:
打印xpath查询:错误的节点集大小
sys.exit(1)
如果res [0] .name!=doc或res [1] .name!=foo:
打印xpath查询:错误节点设置值
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
ElementTree XPath使用示例
from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file ='tst.xml')
for e in mydoc.findall ('/ foo / bar'):
print e.get('title')。text
What is the library? Is there a full implementation? How is the library used? Where is its website?
解决方案
libxml2 has a number of advantages:
- Compliance to the spec
- Active development and a community participation
- Speed. This is really a python wrapper around a C implementation.
- Ubiquity. The libxml2 library is pervasive and thus well tested.
Downsides include:
- Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries.
- Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
- Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.
If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.
Sample of libxml2 XPath Use
import libxml2
doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
print "xpath query: wrong node set size"
sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
print "xpath query: wrong node set value"
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
Sample of ElementTree XPath Use
from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
print e.get('title').text
这篇关于如何在Python中使用Xpath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文