Search code examples
xmlxsltsubstr

Substring the result of for loop in XSL


Seeking one help on xsl payment file template. I have to restrict the length of a tag after for loop to 140 characters. In attached xml, after concatenating the DocumentPayable/DocumentNumber/ReferenceNumber, I want to print only 140 characters in Ustrd tag for one payment info tag (i.e. PmtInf). How can this be achieved via xsl? I am attaching the current working xsl template wherein I am able to concatenate the values and xml file which has got the sample data.

<xsl:variable name="varustrd" select="oraext:create-delimited-string (DocumentPayable/DocumentNumber/ReferenceNumber, ',' )"/>

<xsl:for-each select="DocumentPayable">

<Ustrd>
<xsl:value-of select="(DocumentNumber/ReferenceNumber)"/>
</Ustrd>

<Ustrd1>
<xsl:value-of select="$varustrd"/>
</Ustrd1>

Solution

  • You can fill a variable with the concatenation and the output only its first 140 characters:

    <xsl:variable name="char140">
      <xsl:for-each select="DocumentPayable/DocumentNumber/ReferenceNumber">
        <xsl:value-of select="."/>
        <xsl:if test="position() != last()">,</xsl:if>
      </xsl:for-each>
    </xsl:variable>
    <Ustrd>
      <xsl:value-of select="substring($char140,1,140)"/>
    </Ustrd>
    

    If you want to produce multiple <Ustrd> elements, each with 140 characters, you need a recursive template

    <xsl:call-template name="char140">
      <xsl:with-param name="s" select="$char140"/
    </xsl:call-template>
    

    which is defined in a top-level element

    <xsl:template name="char140">
      <xsl:param name="s"/>
      <xsl:if test="$s">
        <Ustrd>
          <xsl:value-of select="substring($s,1,140)"/>
        </Ustrd>
        <xsl:call-template name="char140">
          <xsl:with-param name="s" select="substring($s,141)"/>
        </xsl:call-template>
      </xsl:if>
    </xsl:template>