RE: [xsl] Constructing X number of elements

Subject: RE: [xsl] Constructing X number of elements
From: "Chris Bayes" <chris@xxxxxxxxxxx>
Date: Tue, 21 Aug 2001 16:07:33 +0100
Ilkka,
Although I rarely recommend using for-each this is a case where it can
come in useful.
If your xml looks something like

<?xml version="1.0" ?>
<movies>
<movie name="Alien1" rating="1"/>
<movie name="Alien2" rating="2"/>
<movie name="Alien3" rating="3"/>
<movie name="Alien4" rating="4"/>
</movies>

Then this stylesheet

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
	<xsl:template match="movie">
		<div>
			<xsl:value-of select="@name"/>
			<xsl:for-each
select="//movie[count(preceding::*) &lt; current()/@rating]">
				<img src="star.gif" alt=""/>
			</xsl:for-each>
		</div>
	</xsl:template>
</xsl:stylesheet>

Will give you the result you want. You only have to be sure that you
have enough movie elements as you want stars. If you don't then this
will also work

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
xmlns:s="Ilkka.com">
<s:stars>
	<s:star/>
	<s:star/>
	<s:star/>
	<s:star/>
	<s:star/>
	<s:star/>
</s:stars>
	<xsl:template match="movie">
		<div><xsl:value-of select="@name"/>
		<xsl:for-each
select="document('')//s:star[count(preceding::*) &lt;
current()/@rating]">
			<img src="star.gif" alt=""/>
		</xsl:for-each>
		</div>
	</xsl:template>
</xsl:stylesheet>

Add as many <s:star/> elements as you need for the max number of stars a
movie can have.

Ciao Chris

XML/XSL Portal
http://www.bayes.co.uk/xml


> -----Original Message-----
> From: owner-xsl-list@xxxxxxxxxxxxxxxxxxxxxx 
> [mailto:owner-xsl-list@xxxxxxxxxxxxxxxxxxxxxx] On Behalf Of 
> Ilkka Hartikainen
> Sent: 21 August 2001 14:27
> To: xsl mulberry
> Subject: [xsl] Constructing X number of elements
> 
> 
> Hi!
> 
> How can I produce X number of elements in XSLT, where X is 
> defined in an attribute of an element in the source XML file?
> 
> For example (this isn't rally what I'm doing), I have this in the XML:
> 
> <movie name="Alien" rating="3"/>
> 
> And I'd like to produce as many stars as in the rating, like:
> 
> <div>
>    <img src="star.gif" alt=""/>
>    <img src="star.gif" alt=""/>
>    <img src="star.gif" alt=""/>
> </div>
> 
> I suppose I can't do this with the for-each-construct. Please 
> help, there has to be a way for doing this! :) If someone 
> knows how to do this with Java and Xalan extension elements, 
> it helps too. I just don't see how I could do this, because 
> you can't actually "move" backwards in XSLT via Java 
> extensions. If you have a solution, please help.
> 
> Kind regards,
> Ilkka Hartikainen
> 
> 
> 
>  XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
> 
> 


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


Current Thread