Reputation: 362
Currently I'm working on some XML transformations. It can happen that the input XML doesn't have certain values, which results in empty elements. So the output might look like:
<car>
<category>Combi</category>
<name>VW Passat</name>
<age />
</car>
My question is if there is a global option or something similar to omit this empty elements such as <age />
?
I could check within the transformation if a certain value is existing. Or I could use a Post-Processing to remove empty elements. But I have hope that there is a more elegant way to do it :-)
Upvotes: 1
Views: 1897
Reputation: 3517
I don't believe that there are any serialization options in XQuery that will allow you to omit nilled elements in the output.
I would suggest just using a slightly modified identity which drops the nilled elements to post-process the output. Something like the following should work:
xquery version "1.0";
declare function local:remove-nilled($node as node()) as node()? {
typeswitch($node)
case document-node()
return
document {
for $child in $node/node()
return
local:remove-nilled($child)
}
case element()
return
if($node/node())then
element { node-name($node) } {
$node/attribute(),
for $child in $node/node()
return
local:remove-nilled($child)
}
else()
default
return
$node
};
local:remove-nilled(
document {
<car>
<category>Combi</category>
<name>VW Passat</name>
<age />
</car>
}
)
Upvotes: 4