0
votes

I need to dynamically create XML like the following using XSL. I'd like to feed either the last num attribute or last loop value to the XSL processor Anyone know how to do that?Desired output like the following:

<loops>
<loop num="1">0</loop>
<loop num="2">1001</loop>
<loop num="3">2001</loop>
<loop num="4">3001</loop>
<loop num="5">4001</loop>
<loop num="6">5001</loop>
<loop num="7">6001</loop>
</loops>
1
Why does the loop for num "1" have a value of "0" and not "1"? Also, can you say whether you can use XSLT 2.0 or above? Thanks!Tim C
I only have XSLT 1.0 available for use. I am processing a list of rows returned in a query and the first row in the list is row 0.Miket46
I don't understand the last sentence.In your question you said the input is the value of the last @num (essentially the number of loop nodes to create). If that's not so, please show us the input and explain the logic that needs to applied in order to produce the output.michael.hor257k

1 Answers

1
votes

If your processor supports XSLT 2.0 then this can be very easy:

<xsl:template match="/">
    <loops>
        <xsl:for-each select="1 to input">
            <loop num="{.}">
                <xsl:value-of select="(. - 1) * 1000 + 1" />
            </loop>
        </xsl:for-each>
    </loops>
</xsl:template>

Note that the result will be slightly different from yours:

<?xml version="1.0" encoding="utf-8"?>
<loops>
   <loop num="1">1</loop>
   <loop num="2">1001</loop>
   <loop num="3">2001</loop>
   <loop num="4">3001</loop>
   <loop num="5">4001</loop>
   <loop num="6">5001</loop>
   <loop num="7">6001</loop>
</loops>

Demo: http://xsltransform.hikmatu.com/bdxtpG


The same thing in XSLT 1.0:

<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="/">
    <loops>
        <xsl:call-template name="create-loops">
            <xsl:with-param name="n" select="input"/>
        </xsl:call-template>
    </loops>
</xsl:template>

<xsl:template name="create-loops">
    <xsl:param name="n"/>
    <xsl:if test="$n > 0">
        <xsl:call-template name="create-loops">
            <xsl:with-param name="n" select="$n - 1"/>
        </xsl:call-template>
        <loop num="{$n}">
            <xsl:value-of select="($n - 1) * 1000 + 1" />
        </loop>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

Demo: http://xsltransform.hikmatu.com/3NzcBsJ