I’m running an xsl transition on some xml and need to be able to set some default values on a few tags if they appear as empty. For example, my xml has
<record>
<name>Bob</name>
<latitude>51.23645</latitude>
<longitude>-0.1254</longitude>
<rank></rank>
</record>
<record>
<name>Chantel</name>
<latitude></latitude>
<longitude></longitude>
<rank>5</rank>
</record>
and I would like to set some defaults to output:
<record>
<name>Bob</name>
<latitude>51.23645</latitude>
<longitude>-0.1254</longitude>
<rank>0</rank>
</record>
<record>
<name>Chantel</name>
<latitude>0.00</latitude>
<longitude>0.00</longitude>
<rank>5</rank>
</record>
I thought this would be straightforward but can’t seem to crack it.
Thanks in advance.
Edit: This is what I was trying to do. Still learning so just a fumble in the dark!
<xsl:template match="record">
<xsl:when test="name()='latitude'">
<xsl:element name="latitude">
<xsl:choose>
<xsl:when test="text()=''">
<latitude>0.00</latitude>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="latitude"></xsl:value-of>
</xsl:otherwise>
</xsl:choose>
</xsl:element>
</xsl:when>
</xsl:template>
Try this:
Add more templates to set default values for other tags.
How it works: The first template is known as the “identity template”, and copies nodes from input to output unchanged. The second template matches “rank” nodes without text child nodes (i.e. empty “rank” nodes), copies them to the output with their attributes and then inserts the default.