我正在使用lxml.etree
,我正在尝试允许用户在文档簿中搜索文本。 当用户提供搜索文本时,我使用 exslt match
函数在文档手册中查找文本。 如果文本显示在element.text
内,则匹配效果很好,但如果文本element.tail
则不匹配。
下面是一个示例:
>>> # XML as lxml.etree element
>>> root = lxml.etree.fromstring('''
... <root>
... <foo>Sample text
... <bar>and more sample text</bar> and important text.
... </foo>
... </root>
... ''')
>>>
>>> # User provides search text
>>> search_term = 'important'
>>>
>>> # Find nodes with matching text
>>> matches = root.xpath('//*[re:match(text(), $search, "i")]', search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})
>>> print(matches)
[]
>>>
>>> # But I know it's there...
>>> bar = root.xpath('//bar')[0]
>>> print(bar.tail)
and important text.
我很困惑,因为 text()
函数本身返回所有文本——包括tail
:
>>> # text() results
>>> text = root.xpath('//child1/text()')
>>> print(text)
['Sample text',' and important text']
为什么当我使用 match
函数时不包括tail
?
为什么当我使用匹配功能时,尾巴没有被包括在内?
这是因为在 xpath 1.0 中,当给定节点集时,match()
函数(或任何其他字符串函数,如 contains()
、starts-with()
等)只考虑第一个节点。
您可以使用//text()
并在单个文本节点上应用正则表达式匹配过滤器,然后返回文本节点的父元素,如下所示:
xpath = '//text()[re:match(., $search, "i")]/parent::*'
matches = root.xpath(xpath, search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})