Re: [xsl] looping on a line (XSLT 1.0 solution)

Subject: Re: [xsl] looping on a line (XSLT 1.0 solution)
From: JBryant@xxxxxxxxx
Date: Tue, 29 Nov 2005 09:30:29 -0600
> could you give an example of a a recursive
> function looping on substring-before()?

Slow day here, so...

Given the following XML file (yours with a parent element):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<d>
  <data>389,456,789</data>
  <data>912</data>
  <data>917,421</data>
  <data>389,456,789,561,123,754</data>
</d>

And given the following transform:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="d">
    <nos>
      <xsl:apply-templates/>
    </nos>
  </xsl:template>

  <xsl:template match="data">
    <xsl:call-template name="separate-at-comma">
      <xsl:with-param name="in-string" select="."/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="separate-at-comma">
    <xsl:param name="in-string"/>
    <xsl:choose>
      <xsl:when test="contains($in-string, ',')">
        <no><xsl:value-of select="substring-before($in-string, 
',')"/></no>
        <xsl:call-template name="separate-at-comma">
          <xsl:with-param name="in-string" 
select="substring-after($in-string, ',')"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <no><xsl:value-of select="$in-string"/></no>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

I get the following results:

<?xml version="1.0" encoding="UTF-8"?>
<nos>
  <no>389</no>
  <no>456</no>
  <no>789</no>
  <no>912</no>
  <no>917</no>
  <no>421</no>
  <no>389</no>
  <no>456</no>
  <no>789</no>
  <no>561</no>
  <no>123</no>
  <no>754</no>
</nos>

Tested with Saxon 8.6 and Xalan-Java 2.4.1.

Also, you can find very good examples of solving this problem in Dave 
Pawson's XSLT FAQ. Here's a link to the Comma Separated Data page in the 
FAQ:

http://www.dpawson.co.uk/xsl/sect2/N1755.html

Jay Bryant
Bryant Communication Services
(presently consulting at Synergistic Solution Technologies)

Current Thread