Mohamed Uvais M
Mohamed Uvais M

Reputation: 305

Creating elements based on values in XSLT

I'm new to XSLT.
I have a source XSLT like the below one.

<?xml version="1.0" encoding="UTF-8"?> 
   <root>
      <child-value>3</child-value>
   </root>

My target should have something like the below one

<?xml version="1.0" encoding="UTF-8"?> 
 <pass_details>
    <pass id ='p1'>1</pass>
    <pass id ='p2'>2</pass>
    <pass id ='p3'>3</pass>
 </pass_details>

The number of <pass> tag should be based on the value of child-value tag? Can any one help with the xslt?

Upvotes: 0

Views: 670

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

If you're limited to XSLT 1.0, you will have to call a recursive template to generate the pass elements:

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

<xsl:template match="/root">
    <pass_details>
        <xsl:call-template name="gen">
            <xsl:with-param name="n" select="child-value"/>
        </xsl:call-template>
    </pass_details>
</xsl:template>

<xsl:template name="gen">
    <xsl:param name="n"/>
    <xsl:if test="$n > 0">
        <xsl:call-template name="gen">
            <xsl:with-param name="n" select="$n - 1"/>
        </xsl:call-template>
        <pass id="p{$n}">
            <xsl:value-of select="$n"/>
        </pass>
    </xsl:if>   
</xsl:template>

</xsl:stylesheet>

Upvotes: 4

Related Questions