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>

 


1 kommentar

Dedicated servers · augusti 16, 2017 kl. 3:17 f m

We’ll start by looking at ways to use these functions to split up strings and how a PCDATA element might be split into subelements. If it finds it, it returns everything in the first parameter’s string before that occurrence of the second string.

Kommentera

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