Home > database >  xml for loop in foreach loop
xml for loop in foreach loop

Time:11-10

I want to insert a for loop inside a foreach loop in xml file but I cant do that

catalog.xml:

<?xml version="1.0" encoding="UTF-8"?>
<movies>
  <cd>
    <title>Avatar</title>
  </cd>
  <cd>
    <title>Captain America</title>
  </cd>
  <cd>
    <title>Ironman</title>
  </cd>
</movies>

xsl:

<?php
  $loop = 2;
?>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <table border="1">
      <xsl:for-each select="movies/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Result: Avatar Captain America Ironman

Let say I only want the foreach loop to run certain time only by the count of the variable $loop(if $loop=2 the it will run 2 times only)?

Expected Result:

$loop =2;

**Avatar
Captain America**

CodePudding user response:

The xsl:for-each instruction is not a "loop". Each node in the selected node-set is processed independently, and there is no exit condition.

If you want to limit the processing to the first 2 cds only, you can do simply:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/movies">
    <html>
        <body>
            <table border="1">
                <xsl:for-each select="cd[position() &lt;= 2]">
                    <tr>
                        <td>
                            <xsl:value-of select="title"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>

</xsl:stylesheet>
  • Related