2

Having trouble figuring out a simple XSLT loop that counts and returns the name of the actor.

<stars>
  <star ID="001">Leonardo DiCaprio</star>
  <star ID="002">Matt Damon</star>
  <star ID="003">Jack Nicholson</star>
</stars>

This is what I made to give the result I wanted but if there was a fourth or fifth actor I would need to add to the code.

<xsl:value-of select="stars/star[@ID='001']"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="stars/star[@ID='002']"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="stars/star[@ID='003']"/>

Basically I need the loop to display the name of the star separated by a comma. Any help is appreciated.

1
  • Good question, +1. See my answer for the simplest solution of all. Note that not a single explicit conditional XSLT instruction or any xsl:for-each needs to be used. :) Commented Aug 12, 2011 at 13:09

3 Answers 3

2

Use a template instead of looping. XSLT processors are optimized for template matching.

<xsl:template match="star">
  <xsl:value-of select="." />
  <xsl:if test="position() != last()">
    <xsl:text>, </xsl:text>
  </xsl:if>
</xsl:template>
Sign up to request clarification or add additional context in comments.

1 Comment

You'll probably need a check for the last star node to prevent an unnecessary comma being put on the end.
1

You can use repetition instruction (without any worry about performance):

<xsl:template match="stars">
    <xsl:value-of select="star[1]"/>
    <xsl:for-each select="star[position()>1]">
        <xsl:value-of select="concat(', ',.)"/>
    </xsl:for-each>
</xsl:template>

gets:

Leonardo DiCaprio, Matt Damon, Jack Nicholson 

Comments

1

This is probably one of the simplest transformations -- note that there is neither need for xsl:for-each nor for any explicit XSLT conditional instruction:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="star[position() >1]">
  <xsl:text>, </xsl:text><xsl:apply-templates/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided source XML document:

<stars>
    <star ID="001">Leonardo DiCaprio</star>
    <star ID="002">Matt Damon</star>
    <star ID="003">Jack Nicholson</star>
</stars>

the wanted, correct output is produced:

Leonardo DiCaprio, Matt Damon, Jack Nicholson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.