Remove Empty XML elements

Often we will be asked to remove the empty elements from XMLs but it will be a dauting task if think of doing it in ESQL. But fortunately XSL has a simple solution which takes care of this in a few lines of code. The below is an example for the same. This one removes all elements which are simple types ( I mean those which doesn’t have value and simple type )

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="node()|@*">
            <xsl:apply-templates select="node()|@*"/>
    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>

Sometimes we will be asked to remove the empty elements segments regardless of whether it is a simple type or complex type. And again, XSL comes to the rescue. Here is another XSL which does the job for us

<?xml version="1.0" ?>
	xmlns:xsl="" version="1.0">
	<xsl:output omit-xml-declaration="yes" indent="yes" />
	<xsl:template match="node()|SDLT">
			test="count(descendant::text()[string-length(normalize-space(.))>0] | @*[string-length(.)>0])">
				<xsl:apply-templates select="@*|node()" />
	<xsl:template match="@*">
		<xsl:copy />
	<xsl:template match="text()">
		<xsl:value-of select="normalize-space(.)" />

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.