Re: Recursion in XSL

Subject: Re: Recursion in XSL
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Mon, 14 Aug 2000 19:30:43 +0100
Ciaran,

>Is is possible to handle recursion in XSL in the following manner.
>I have a tag:
>
><tag att1="value1" att2="value2" att3="value3">

Do you mean you have a string with this as the value of that string, or do
you mean that you have an empty element?

>I was trying to do this with recursion whereby I'd use:
><xsl:for-each select="@*">
>.....
></xsl:for-each>

That's iteration, not recursion.  Recursion is where you call a function
from within the function itself.  When you cycle over a set of things, it's
called iteration.

>Alternatively, if anyone could suggest a way in which to retrieve all
>the attributes and their values as one string so that I could perform a
>translate on
>them that would achieve the same purpose:
>
>translate($attributeString,'&quot;','|')

This implies that you're dealing with an element in your input XML and you
want to generate, from this element, a string that gives the attributes and
their values in an XML-like syntax that has | rather than quotes.

First, make a template that matches on the element.  This will hold the
XSLT that processes the element attributes and values:

<xsl:template match="tag">
  ...
</xsl:template>

Now, to build up the string, you want, for each attribute, to give its
name, followed by an '=', followed by an '|', followed by the attribute
value, followed by another '|', and followed by a space if it's not the
last attribute in the list.

For this, you need iteration: you want to cycle over the attributes.  You
get hold of the attributes using the XPath "@*", as you've identified.  You
construct the string that you want using xsl:value-of and xsl:text (or a
larger concat() if you want):

<xsl:template match="tag">
  <xsl:for-each select="@*">
    <xsl:value-of select="name()" />
    <xsl:text>=|</xsl:text>
    <xsl:value-of select="." />
    <xsl:text>|</xsl:text>
    <xsl:if test="position() != last()"> </xsl:if>
  </xsl:for-each>
</xsl:template>

You can of course use the same xsl:for-each as the value of a variable, if
you like.

I hope this helps,

Jeni

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


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


Current Thread