官方文档here只是说,“匹配可能是标签名称或路径”,但我在任何地方都没有看到“路径”的定义。通过查看网络上的示例,我发现它是一些类似 XPath 的简化表示法,但不清楚到底允许什么——例如,路径是否应该以 /
开头,或者以 开头//
,或者根本没有分隔符?我可以使用 [@att = "value"]
指定属性吗?
最佳答案
好吧,查看源代码http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py我们发现 Element.find
的实现为
def find(self, path, namespaces=None):
return ElementPath.find(self, path, namespaces)
ElementPath
实现为
try:
from . import ElementPath
except ImportError:
ElementPath = _SimpleElementPath()
_SimpleElementPath
仅检查标签名称:
# emulate pre-1.2 find/findtext/findall behaviour
def find(self, element, tag, namespaces=None):
for elem in element:
if elem.tag == tag:
return elem
return None
让我们看看ElementPath.py:http://hg.python.org/cpython/file/f98e2944cb40/Lib/xml/etree/ElementPath.py它指出,
# limited xpath support for element trees
所以我假设有效的 XPath 可能是 find
的有效参数。我对 XPath 不太熟悉,无法确定它到底支持什么,但是http://effbot.org/zone/element-xpath.htm描述了五年前它支持的程度,并包含一个语法表。
ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.
http://docs.python.org/dev/library/xml.etree.elementtree.html#xpath-support有一个更新的表。看起来并没有太大不同。
关于python - ElementTree: 'match' 方法的 'find' 参数的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731040/