zyberjock
zyberjock

Reputation: 347

Set a Default value for each empty XML tags in XSLT 1.0

I need to write a default text or number to an empty XML tag using XSLT 1.0, then upon searching here in StackOverflow I happen to look at the solution of Dimitre in this post

What I need is for example I have a tag like below:

<Number></Number> <!--Which is empty--> 

or

<Text></Text> <!--Which is also empty-->

What I need is to put a Default value for each empty tags in my XML like <Number>0.00</Number> for numeric tags and <Text>nil</Text> for Alphanumeric tags, I have quite a big XML so is there any way to make it like an identity template where it will always be read from my input then transform it to Insert the default on empty strings or I can only do the code like below on each field/tags?

<xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>

Thanks in advance.

Upvotes: 2

Views: 2599

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

This transformation:

<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="Number[not(node())]">
    <Number>0.00</Number>
  </xsl:template>

  <xsl:template match="Text[not(node())]">
    <Text>nill</Text>
  </xsl:template>
</xsl:stylesheet>

when applied on this XML document (as none was provided):

<t>
  <Number>10</Number>
  <Number/>
  <Text>Hello</Text>
  <Text/>
</t>

produces the wanted, correct result:

<t>
   <Number>10</Number>
   <Number>0.00</Number>
   <Text>Hello</Text>
   <Text>nill</Text>
</t>

Note:

In order to get the systematic knowledge to solve basic problems like this, I (shamelessly) recommend to watch this Pluralsight training course:

XSLT 2.0 and 1.0 Foundations

Upvotes: 2

Related Questions