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"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>
</xsl:stylesheet>

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" ?>
<xsl:stylesheet
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<xsl:output omit-xml-declaration="yes" indent="yes" />
	<xsl:template match="node()|SDLT">
		<xsl:if
			test="count(descendant::text()[string-length(normalize-space(.))>0] | @*[string-length(.)>0])">
			<xsl:copy>
				<xsl:apply-templates select="@*|node()" />
			</xsl:copy>
		</xsl:if>
	</xsl:template>
	<xsl:template match="@*">
		<xsl:copy />
	</xsl:template>
	<xsl:template match="text()">
		<xsl:value-of select="normalize-space(.)" />
	</xsl:template>
</xsl:stylesheet>

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.