【发布时间】:2010-11-21 14:33:38
【问题描述】:
在处理 XML 时是否可以在 Python 中使用 XPath 查询。我正在使用不支持该功能的 minidom。还有其他模块吗?
【问题讨论】:
标签: python python-3.x
在处理 XML 时是否可以在 Python 中使用 XPath 查询。我正在使用不支持该功能的 minidom。还有其他模块吗?
【问题讨论】:
标签: python python-3.x
http://docs.python.org/library/xml.etree.elementtree.html
etree 支持 XPath 查询,就像 lxml。
etree 包含在标准库中,但 lxml 更快。
【讨论】:
包含元素树。在 2.6 及以下它的 xpath 非常弱,但在 2.7 much improved:
import xml.etree.ElementTree as et
root = et.parse(filename)
result = ''
# How to make decisions based on attributes even in 2.6
for e in root.findall('.//child/grandchild'):
if e.attrib.get('name') == 'foo':
result = e.text
break
【讨论】: