IBM Support

How to set an empty element with an attribute xsl:nil=true using XSLT?

Question & Answer


Question

How to set an empty element with an attribute xsl:nil=true using XSLT?

Answer

Below is the xslt which will set the empty element attribute xsi:nil="true".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
    <xsl:template match="*">
        <xsl:choose>
            <xsl:when test="count(*|text()[string-length(normalize-space(.))>0])">
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:attribute name="xsi:nil">true</xsl:attribute>
                    <xsl:value-of select="."/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="text()[string-length(normalize-space(.))>0]">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>
    <xsl:template match="text()"/>
</xsl:stylesheet>

for example if the my xml file is as below

<?xml version="1.0" encoding="UTF-8"?>
<Test_Nill>
   <Records>
        <LastName>LastName</LastName>
        <FirstName>FirstName</FirstName>
        <MobileNo>MobileNo</MobileNo>
        <EMailAddr></EMailAddr>
        <Address>asdfasd</Address>
     </Records>
  </Test_Nill>

As you can see that  <EMailAddr></EMailAddr> is empty and you want to set this field to nillable so that the it becomes  <EMailAddr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />.
The output of the xslt will be as below

<?xml version="1.0" encoding="UTF-8"?>
<Test_Nill>
   <Records>
        <LastName>LastName</LastName>
        <FirstName>FirstName</FirstName>
        <MobileNo>MobileNo</MobileNo>
<EMailAddr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />         <Address>asdfasd</Address>
     </Records>
  </Test_Nill>

[{"Product":{"code":"SSGR73","label":"IBM Cast Iron Cloud Integration"},"Business Unit":{"code":"BU053","label":"Cloud & Data Platform"},"Component":"Not Applicable","Platform":[{"code":"PF033","label":"Windows"}],"Version":"5.0.1.7;5.0.1.8;6.1.0.9","Edition":"Virtual;Physical;Cloud","Line of Business":{"code":"LOB45","label":"Automation"}}]

Historical Number

00000427

Product Synonym

Cast Iron Solution
Cast Iron Operating System
Cast Iron Studio

Document Information

More support for:
IBM Cast Iron Cloud Integration

Software version:
5.0.1.7, 5.0.1.8, 6.1.0.9

Operating system(s):
Windows

Document number:
410657

Modified date:
15 June 2018

UID

swg21453035

Manage My Notification Subscriptions