Split strings in XSLT 1

More than 15 years after introducing XSLT 2 and more than 8 years after introducing XSLT 3, XSLT 1 is still being used frequently by many users. One of the difficulties that I experienced with XSLT 1 is simple String operations. In this post I will write the way for splitting strings in XSLT 1 which can be used in higher version as well.

The task is to split a string containing periods and for every substring if it contains whitespaces in the middle of it (not in beginning or end of substring) then surrounding it with single quotation marks. For example for the input “C.Program Files (x86).Internet Explorer “, the output should be “C.’Program Files (x86)’.’Internet Explorer’“.

<!--=============Function definitions  ========================-->
<xsl:template name="recursiveAddQuoteMark">
  <xsl:param name="string"/>
  <xsl:param name="separator" select="'.'"/>
  <xsl:choose>
      <xsl:when test="not(contains($string,  $separator))">
          <xsl:call-template name="addQuotMark">
              <xsl:with-param name="string" select="normalize-space($string)"/>
          </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
          <xsl:variable name="prefix">
              <xsl:call-template name="addQuotMark">
                  <xsl:with-param name="string" select="normalize-space(substring-before($string, $separator))"/>
              </xsl:call-template>
          </xsl:variable>
          <xsl:variable name="suffix">
              <xsl:call-template name="recursiveAddQuoteMark">
                  <xsl:with-param name="string" select="substring-after($string, $separator)"/>
              </xsl:call-template>
          </xsl:variable>
          <xsl:value-of select="concat($prefix, $separator, $suffix)"/>
      </xsl:otherwise>
  </xsl:choose>
</xsl:template>


<xsl:template name="addQuotMark">
  <xsl:param name="string"/>
  <xsl:param name="space" select="' '"/>
  <xsl:choose>
      <xsl:when test="contains($string,  $space)">
          <xsl:value-of select='concat("&apos;",$string , "&apos;")'/>
      </xsl:when>
      <xsl:otherwise>
          <xsl:value-of select="$string"/>
      </xsl:otherwise>
  </xsl:choose>
</xsl:template>

 

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *