递归替换

recursive replacement

如何在不使用 xquery 更新的情况下找到所有空字符串并将其替换为 xquery 中的 'empty' 元素。我使用 xquery update 实现了这一点,但我想在不使用 update 的情况下获得。

这种转换在 XSLT 中更容易。在 XSLT 3.0 中,您可以这样写:

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">    
  <xsl:mode on-no-match="shallow-copy"/>    
  <xsl:template match="*[.='']"><empty/></xsl:template>    
</xsl:transform>

这样做的原因是 "on-no-match='shallow-copy'" 导致输入树的递归处理,如果没有针对特定元素的显式模板规则,处理器只是复制该元素并向下递归处理它children.

XQuery 没有 built-in 原语来执行此操作,但您可以通过显式写出它来实现相同的目的。你需要一个递归函数:

declare function local:process($e as node()) as node() {
  if ($e[self::element()])
  then 
    if ($e='')
    then <empty/>
    else
      element {node-name($e)} {
        $e/@*,
        $e/child::node()/local:process(.)
      }
  else (:text, comment, PI nodes:)
    $e
};

local:process($in/*)