Home > database >  Every loop should repeat twice in xslt
Every loop should repeat twice in xslt

Time:06-11

Basically i need to repeat each child loop twice one after the other. In the below example 'apple' should repeat twice then 'mango' should repeat twice

XML:

<?xml version="1.0" encoding="Windows-1252" standalone="no"?>
<root >
    <child id="123">
        <fruit>apple</fruit>
        <comment>This is 1st line</comment>
    </child>         
   <child id="345">
        <fruit>mango</fruit>
        <comment>This is 2nd line</comment>
    </child>
</root>

XSLT:

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

    <xsl:template match="/">
<xsl:param name="pack" select="2"></xsl:param>

    <xsl:for-each select="root/child">
<xsl:for-each select="(//node())[position() &lt;= $pack]">
        
<xsl:text>&#xA;</xsl:text>
        <xsl:value-of select="//fruit"/>

          
         <xsl:text>&#xA;</xsl:text>
       <xsl:value-of select="//comment"/>
<xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
</xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Current o/p:


apple This is 1st line

apple This is 1st line

apple This is 1st line

apple This is 1st line


Expected:


apple This is 1st line

apple This is 1st line

mango This is 2nd line

mango This is 2nd line


Your help is much appreciated!

CodePudding user response:

In XSLT 1.0 you would need to do something like:

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

<xsl:param name="pack" select="2"/>

<xsl:template match="child" name="repeat">
    <xsl:param name="times" select="$pack"/>
    <xsl:if test="$times > 0">
        <xsl:value-of select="fruit"/>
        <xsl:text>&#xA;</xsl:text>
        <xsl:value-of select="comment"/>
        <xsl:text>&#xA;</xsl:text>
        <!-- recursive call -->
        <xsl:call-template name="repeat">
            <xsl:with-param name="times" select="$times - 1"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
  • Related