Search code examples
xsltis-empty

XSLT for converting empty body to a SUCCESS message


I am trying to replace an empty response body, which is getting generated by a successful DELETE operation with a "Success" message via XSLT.

Can anyone help me with the XSLT which can simply print a SUCCESS message, if the response body is empty.

Response Body will be: <response status="204"> </response>

Expected output: <response status="204">SUCCESS</response>

Update from comment: If the response is not empty then it should print the same what comes back as a response.

Currently using the below XSLT:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" 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(*) and not(normalize-space())]">
        <xsl:element name="{name()}" namespace="{namespace-uri()}"/>
    </xsl:template>
</xsl:stylesheet>

But it gives: <response/> as output.


Solution

  • Can anyone help me with the XSLT which can simply print a SUCCESS message, if the response body is empty.

    If the response is not empty then it should print the same what comes back as a response.

    Then try:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="/response[not(node())]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:text>SUCCESS</xsl:text>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>