Re: [xsl] Replace character with line brake in long string

Subject: Re: [xsl] Replace character with line brake in long string
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Fri, 11 Oct 2002 14:26:24 +0100
Hi Jussi,

> I have an xml file including the following elements (string can be
> even longer):
>
>  <attribute>
>    <name>Ranges</name>
>    <string>Amplifier IC|Analog Switch|Mixer IC|Modulator IC|Negative Voltage Regulator|Other Analog IC|Phase Locked Loop|Positive Voltage Regulator|Switching PSU Controller IC</string>
>  </attribute>
>
> What I would like to get with xsl is
>
>         <tr>
>         <td>
>         Amplifier IC<br/>
>         Analog Switch<br/>
>         Mixer IC<br/>
>         Modulator IC<br/>
>         Negative Voltage Regulator<br/>
>         Other Analog IC<br/>
>         Phase Locked Loop<br/>
>         Positive Voltage Regulator<br/>
>         Switching PSU Controller IC<br/>
>         </td>
>         </tr>

There are a couple of approaches. One is to use an extension
str:tokenize() function to tokenise your string and then use
xsl:for-each to iterate over the results. Another is to use a
recursive template to walk through the string with substring-before()
and substring-after() to replace the |s with <br />s. For example:

<xsl:template name="replace">
  <xsl:param name="string" select="." />
  <xsl:choose>
    <xsl:when test="not($string)" />
    <xsl:when test="contains($string, '|')">
      <xsl:value-of select="substring-before($string, '|')" />
      <br />
      <xsl:call-template name="replace">
        <xsl:with-param name="string"
                        select="substring-after($string, '|')" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$string" />
      <br />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

You could call this template from a template matching the string
element as follows:

<xsl:template match="string">
  <tr>
    <td>
      <xsl:call-template name="replace" />
    </td>
  </tr>
</xsl:template>

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread