Re: [xsl] repeat and replace loop ( at the same time )

Subject: Re: [xsl] repeat and replace loop ( at the same time )
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Sat, 6 Apr 2002 15:37:27 +0100
Hi PG,

> With my xslt stylesheet, i always copy the first record and the last
> record also. But these should not be repeated.

OK, so you have the template and data set up in variables as follows:

<xsl:variable name="template" select="/root/table/record"/>
<xsl:variable name="data" select="document('replace_data.xml')/root/record"/>

You want to create a table element that contains the first record from
the template, several records created from each record of the data,
and then the last record from the template:

<xsl:template match="/">
  <table>
    <xsl:copy-of select="$template[1]" />
    <xsl:apply-templates select="$data" />
    <xsl:copy-of select="$template[last()]" />
  </table>
</xsl:template>

Then you need a template that matches records (in the data):

<xsl:template match="record">
  <xsl:variable name="record" select="." />
  ...
</xsl:template>

For each of those records, you want to use the information from the
records in the template (aside from the first and last ones) to create
a record in the result:

<xsl:template match="record">
  <xsl:variable name="record" select="." />
  <xsl:for-each select="$template[position() != 1 and
                                  position() != last()]">
    <record>
      ...
    </record>
  </xsl:for-each>
</xsl:template>

The content of the record is determined by the value of the namedcell
name. If it's 'ordernr' then you want the ordernr attribute from the
order element child of the $record. Otherwise, you want the value of
the element child of the $record with the same name as the namedcell.
So you need something like:

<xsl:template match="record">
  <xsl:variable name="record" select="." />
  <xsl:for-each select="$template[position() != 1 and
                                  position() != last()]">
    <xsl:variable name="namedcell" select="namedcell" />
    <record>
      <data>
        <xsl:choose>
          <xsl:when test="$namedcell/@name = 'ordernr'">
            <xsl:value-of select="$record/order/@ordernr" />
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$record/*[name() =
                                            $namedcell/@name]" />
          </xsl:otherwise>
        </xsl:choose>
      </data>
      <xsl:copy-of select="$namedcell" />
    </record>
  </xsl:for-each>
</xsl:template>

Cheers,

Jeni

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


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


Current Thread