Search code examples
xmlxslt-1.0xslt-2.0xslt-3.0

lnamest and nameend change into colspan


I want to change the namest and nameend attribute value into the the colspan attribute value

XML Input:

<row>
    <entry nameend="col2" namest="col1">Claims</entry>
</row>

XSL I'm having:

<xsl:template match="row">
    <tr>
      <xsl:apply-templates/>
    </tr>
  </xsl:template>
  
  <xsl:template match="entry">
    <td>
      <xsl:apply-templates/>
    </td>
  </xsl:template>

Expected Output is:

 <tr>
    <td colspan="2">Claims</td>
</tr>

If the namest="1" and nameend="3", the colspan value would be 3. It have to depend on namest and nameend values. It have to calculate the numbers from namest and nameend.


Solution

  • It is hard to come up with an algorithm based on a single example, with no rules given. The following should work for your input above:

    <xsl:template match="entry">
        <xsl:variable name="start" select="substring-after(@namest, 'col')" />
        <xsl:variable name="end" select="substring-after(@nameend, 'col')" />
        <td colspan="{$end - $start + 1}">
            <xsl:apply-templates/>
        </td>
    </xsl:template>
    

    This is assuming you are using XSLT 1.0. If you are using an XSLT 2.0 processor and your stylesheet is tagged as version="2.0" then you need to do:

    <xsl:template match="entry">
        <xsl:variable name="start" select="number(substring-after(@namest, 'col'))" />
        <xsl:variable name="end" select="number(substring-after(@nameend, 'col'))" />
        <td colspan="{$end - $start + 1}">
            <xsl:apply-templates/>
        </td>
    </xsl:template>