我正在使用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?
发布于 2015-06-12 08:52:18
当我使用match函数时,为什么尾部没有包括在内?
这是因为在XPath1.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'})https://stackoverflow.com/questions/30791112
复制相似问题