Remove Empty tags using XSLT

While performing xslt transform on source XML, we may need not to include empty tags in the output xml payload. 

Sample scenarios:
    1. Target system doesn't want empty tags to come.
    2. Size of xml payload has become huge due to unwanted empty tags.

Source XML

Output XML

The optimal way to achieve above result is to use conditional if statement in xslt i.e. xsl:if

Sample XSLT
<xsl:if test="/inRoot/t2!=''">
        <xsl:value-of select="ns0:C1"/>

If we have some whitespaces included between tags, the above if-statement may fail and in such scenarios, we may use normalize-space() function in xslt and test condition will become : "normalize-space(/inRoot/t2)!=''"

Sometimes, we just want to remove empty elements from already transformed xml. Such cases have same input and output schemas. In such scenarios we can take leverage of identity transform using xsl templates and copy methods. See the below sample xslt identity transform to remove empty tags.

Sample XSLT:
<xsl:template match="node()|@*">
    <xsl:if test="normalize-space(.) !='' or ./@* !=''">
      <xsl:copy-of select="@*"/>

If we are using xslt in JDev, we need to specify input and output schemas and replace xsl:template tag with the above xsl template code.


Post a Comment

Popular posts from this blog

DateTime formatting using xp20:format-dateTime ()

Create Delimited String from XML Nodes and Vice Versa in SOA 12c

Import and Export MDS artifacts in SOA 12c