xmlxsltxsl-variable

Generat new nodes at XSLT file with loop and variables


Need your help. I have some XML file with data before the transformation.

<?xml version="1.0" encoding="UTF-8"?>
<Envelope>
  <filter>
    <type>book</type>
    <pageLimit>200</pageLimit>
    <brand>1</brand>
  </filter>
</Envelope>

And I have an XSLT file. But during transformation, I need to add new nodes to this XSLT file. And the funny thing is that I need to generate this node for example 10 times with numeric ascending (but I don't want to write this stuff by hands).

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/">
        <Envelope>
          <filter>
            <type>
              <xsl:value-of select="/Envelope/filter/type"/>
            </type>
            <pageLimit>
              <xsl:value-of select="/Envelope//filter/pageLimit"/>
            </pageLimit>
            <brand>
              <xsl:value-of select="/Envelope/filter/brand"/>
            </brand>
          </filter>
          
        </Envelope>
    </xsl:template>
</xsl:stylesheet>

In output XML file should look somthing like this:

<Envelope>
   <filter>
      <type>book</type>
      <pageLimit>200</pageLimit>
      <brand>1</brand>
   </filter>
   <item>1</item>
   <item>2</item>
   <item>3</item>
   <item>4</item>
   <item>5</item>
   <item>6</item>
   <item>7</item>
   <item>8</item>
   <item>9</item>
   <item>10</item>   
</Envelope>

I think it is possible to use some variables at XSLT to generate this stuff. But I don't know how to do that. Thanks so much for your help =)


Solution

  • Assuming your are really using an XSLT 2 or later processor with XPath 2 or later it is as easy as knowing that 1 to 10 constructs the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and that way to implement

    <xsl:for-each select="1 to 10">
      <item>
        <xsl:value-of select="."/>
      </item>
    </xsl:for-each>