如何在 Python 中使用 XPath? [英] How to use XPath in Python?

查看:37
本文介绍了如何在 Python 中使用 XPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

支持 XPath 的库有哪些?有完整的实现吗?图书馆是如何使用的?它的网站在哪里?

What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?

推荐答案

libxml2 有很多优点:

  1. 遵守规范
  2. 积极开发和社区参与
  3. 速度.这实际上是一个围绕 C 实现的 Python 包装器.
  4. 无处不在.libxml2 库无处不在,因此经过充分测试.

缺点包括:

  1. 符合规范.很严格.在其他库中,诸如默认命名空间处理之类的事情更容易.
  2. 使用本机代码.这可能会很痛苦,具体取决于您的应用程序的分发/部署方式.可以使用 RPM 来缓解这种痛苦.
  3. 手动资源处理.请注意以下示例中对 freeDoc() 和 xpathFreeContext() 的调用.这不是很 Pythonic.
  1. Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries.
  2. 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.
  3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.

如果您要进行简单的路径选择,请坚持使用 ElementTree(包含在Python 2.5).如果您需要完全符合规范或原始速度并且可以应对本机代码的分发,请使用 libxml2.

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.

libxml2 XPath 使用示例

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()

ElementTree XPath 使用示例

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆