0

How to find all the empty string and replace it with 'empty' element in xquery without using xquery updating. I achieved this using xquery update but I want to get without using update.

SS2
  • 3
  • 2

1 Answers1

4

This kind of transformation is easier in XSLT. In XSLT 3.0 you could write:

<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>

The reason this works is that "on-no-match='shallow-copy'" causes a recursive processing of the input tree, where if there is no explicit template rule for a particular element, the processor just copies the element and recurses down to process its children.

XQuery doesn't have a built-in primitive to do this, but you can achieve the same thing by writing it out explicitly. You need a recursive function:

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/*) 
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • The `$e/@*` copies attributes for the elements that aren't changed. If you want the empty element to retain attributes, do `{$e/@*}` – Michael Kay Mar 19 '18 at 14:19