Can not use translate() method in xpath with lxml etree

Question:

I want to use translate to lower my text with lxml library in Python. My code is as below

r = element.xpath('./a/translate(text(), "A", "a")')

But it give me an exception:

lxml.etree.XPathEvalError: Invalid expression

I’d like to do this with xpath only (without writing code in Python). Please give me a solution. Thanks

Asked By: Tú Phạm

||

Answers:

You may try following code by wrapping up the translate outside

from lxml import etree

xml = '''<root>
    <a>A TEXT CONTENT</a>
</root>'''

root = etree.fromstring(xml)
element = root.xpath('translate(./a/text(), "A", "a")')
print(element)

Result

a TEXT CONTENT

You can also specify more translation rules

element = root.xpath('translate(./a/text(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")')

Result

a text content
Answered By: Tấn Nguyên
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.