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
<inRoot>
    <t1>Hello</t1>
    <t2></t2>
    <t3>World</t3>
</inRoot>

Output XML
<outRoot>
    <a1>Hello</a1>
    <a3>World</a3>
</outRoot>

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!=''">
    <a2>
        <xsl:value-of select="ns0:C1"/>
    </a2>
</xsl:if>

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>
      <xsl:copy-of select="@*"/>
        <xsl:apply-templates/>
      </xsl:copy>
    </xsl:if>
</xsl:template>

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.


Comments

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