Anirban
Anirban

Reputation: 949

Applying default values in multiple XML elements using XSLT 1.0

I am using XSLT 1.0. There is a requirement of applying default values to all the XML elements which are blank using XSLT. For example, say below is the input XML:

<employee>
    <id attributeName="attributeValue">1111</id>
    <name attributeName="attributeValue" />
    <address attributeName="attributeValue" />
</employee>

Here the value of XML elements name and address are blank. I need to fill those with default values so that the XML will look like the below:

<employee>
    <id attributeName="attributeValue">1111</id>
    <name attributeName="attributeValue">default</name>
    <address attributeName="attributeValue">default</address>
</employee>

Can anyone please suggest me how to do this using XSLT 1.0? Sorry if the question is naive as I am not an expert in XSLT.

Upvotes: 0

Views: 42

Answers (1)

y.arazim
y.arazim

Reputation: 3162

You could use a simple modification of the identity transform template:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:if test="not(node())">default</xsl:if>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions