如何检查 typeswitch 表达式中的动态元素名称?

How to check for dynamic element names in a typeswitch expression?

此问题与有关。

import module namespace functx = "http://www.functx.com" at "MarkLogic/functx/functx-1.0-doc-2007-01.xqy";
declare function local:change($node) 
{ 
  typeswitch($node) 
    case element(add) return 
      functx:add-attributes($node, xs:QName('att1'), 1)
    case element() return 
      element { fn:node-name($node) } { 
        $node/@*, 
        $node/node() ! local:change(.)
      } 
    default return $node 
};
let $test := <test>
                <add>x1</add>
                <c><add>x2</add></c>
                <b>x</b>
             </test>

return local:change($test)

需要动态检查要添加属性的元素。它是从外部驱动的。因此,我尝试将要添加的元素的名称作为参数发送给 local:change 函数,但 typeswitch case 不接受动态值。如何检查这是 typeswitch 表达式?

Typeswitch 只允许固定的元素名称,而不是 XQuery 定义的变量。不要匹配 typeswitch 中的 <add/> 元素,而是匹配所有元素并使用 local-name(...)(如果必须匹配名称空间,则使用 name(...))来区分值。

import module namespace functx = "http://www.functx.com" at "MarkLogic/functx/functx-1.0-doc-2007-01.xqy";
declare function local:change($node, $name) 
{ 
  typeswitch($node) 
    case element() return 
      if (local-name($node) eq $name)
      then
        functx:add-attributes($node, xs:QName('att1'), 1)
      else element { fn:node-name($node) } { 
          $node/@*, 
          $node/node() ! local:change(., $name)
        } 
    default return $node 
};
let $test := <test>
                <add>x1</add>
                <c><add>x2</add></c>
                <b>x</b>
             </test>

return local:change($test, "add")