Skip to content
Snippets Groups Projects
Commit cd902d73 authored by Ladislav Lhotka's avatar Ladislav Lhotka
Browse files

Implement XPath function translate().

parent 8c14ca69
No related branches found
No related tags found
No related merge requests found
......@@ -376,6 +376,8 @@ def test_xpath(instance):
xptest("string-length() = 6", node=lr)
xptest("""normalize-space(' \tfoo bar
baz ')""", "foo bar baz")
xptest("translate(., 'ABCDEF', 'abcdef')", "c0ffee", lr)
xptest("translate('--abcd--', 'abc-', 'ABC')", "ABCd")
def test_instance_paths(data_model, instance):
rid1 = data_model.parse_resource_id("/test:contA/testb:leafN")
......
......@@ -560,6 +560,18 @@ class FuncSubstringBefore(BinaryExpr):
ind = lres.find(rres)
return lres[:ind] if ind >= 0 else ""
class FuncTranslate(BinaryExpr):
def __init__(self, s1: Expr, s2: Expr, s3: Expr) -> None:
super().__init__(s1, s2)
self.nchars = s3
def _eval(self, xctx: XPathContext) -> str:
string, old = self._eval_ops_string(xctx)
new = self.nchars._eval_string(xctx)[:len(old)]
ttab = str.maketrans(old[:len(new)], new, old[len(new):])
return string.translate(ttab)
class FuncTrue(Expr):
def _eval(self, xctx: XPathContext) -> bool:
......@@ -897,6 +909,12 @@ class XPathParser(Parser):
def _func_substring_before(self) -> FuncSubstringBefore:
return FuncSubstringBefore(*self._two_args())
def _func_translate(self) -> FuncTranslate:
s1, s2 = self._two_args()
self.char(",")
self.skip_ws()
return FuncTranslate(s1, s2, self.parse())
def _func_true(self) -> FuncTrue:
return FuncTrue()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment