3

我希望通过使用映射的键和值对来实现对文档中的字符串的查找和替换。由于 2 个映射值,我目前拥有的代码似乎返回了 2 个字符串。我希望返回一个字符串,其中大括号中的值被映射中的值替换。

let $text:='On ${date} the value of alert is ${alerts}'
    let $params:= map:map()
    let $noop:=map:put($params,'date','TESTINGDATE')
    let $noop:=map:put($params,'alerts','TESTALERT')


    let $formatted-message:=for $keys in map:keys($params)
                            let $message:=fn:replace($text,fn:concat('\$\{',$keys,'\}'),map:get($params,$keys))
                            return $message

    return $formatted-message
4

1 回答 1

4

您可以使用递归函数:

declare function local:replace-all($text, $key, $rest, $params) 
{
  if (fn:empty($key)) then
    $text
  else
    local:replace-all(fn:replace($text, fn:concat('\$\{',$key,'\}'), map:get($params,$key)), 
                      fn:head($rest), 
                      fn:tail($rest), 
                      $params)

};

let $text:='On ${date} the value of alert is ${alerts}'
let $params:= map:map()
let $noop:=map:put($params,'date','TESTINGDATE')
let $noop:=map:put($params,'alerts','TESTALERT')
let $keys := map:keys($params)
return
  local:replace-all($text, fn:head($keys), fn:tail($keys), $params)

或者你可以使用fn:fold-left()

let $text:='On ${date} the value of alert is ${alerts}'
let $params:= map:map()
let $noop:=map:put($params,'date','TESTINGDATE')
let $noop:=map:put($params,'alerts','TESTALERT')
let $keys := map:keys($params)
return
  fn:fold-left(
    function($text, $keys) {
      let $key := fn:head($keys)
      return 
        fn:replace($text, fn:concat('\$\{',$key,'\}'), map:get($params,$key))
    },
    $text,
    $keys
  )

两者都产生:

On TESTINGDATE the value of alert is TESTALERT
于 2018-03-21T19:45:19.940 回答