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.
Asked
Active
Viewed 272 times
0
-
Your XQuery and XML snippets have been helpful (because the question itself – finding all empty strings – could be misleading). Maybe you could consider readding them to your question? – Christian Grün Mar 19 '18 at 10:47
-
Yes, I will add – SS2 Mar 19 '18 at 13:01
1 Answers
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