Home > database >  How to fix this in XSLT 3.0? (xsl:iterate and xsl:break)
How to fix this in XSLT 3.0? (xsl:iterate and xsl:break)

Time:09-26

I am trying to experiment with XSLT 3.0 here at https://xsltfiddle.liberty-development.net/ .

I got this error:

xsl:break must be the last instruction in the xsl:iterate loop

Here is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<primes>
   <i>2</i>
   <i>3</i>
   <i>5</i>
   <i>7</i>
   <i>11</i>
   <i>13</i>
</primes>

Here is my XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"    
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"     
       xmlns:xs="http://www.w3.org/2001/XMLSchema"  
       xmlns:fn="http://www.w3.org/2005/xpath-functions">
   <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
   <xsl:template match="/primes">
      <xsl:iterate select="i">
         <xsl:param name="cnt" select="1"/>
         <xsl:choose>
            <xsl:when test="position()=1">
              &#10; Prime: 2
            </xsl:when>
            <xsl:when test="position() le 5">
              &#10; Prime <xsl:value-of select="."/> Leap: 
              <xsl:value-of select=". - /*//i[$cnt - 1]"/>
            </xsl:when>
            <xsl:otherwise>
               <xsl:break/>
            </xsl:otherwise>
         </xsl:choose>
         <xsl:on-completion>
             Primes are fun.
         </xsl:on-completion>
         <xsl:next-iteration>
            <xsl:with-param name="cnt" select="$cnt 1" as="xs:integer"/>
         </xsl:next-iteration>
      </xsl:iterate>
   </xsl:template>
</xsl:stylesheet>

CodePudding user response:

Due to the rules laid out in https://www.w3.org/TR/xslt-30/#iterate you need e.g.

   <xsl:template match="/primes">
      <xsl:iterate select="i">
         <xsl:param name="cnt" select="1"/>
         <xsl:on-completion>
             Primes are fun.
         </xsl:on-completion>
         <xsl:choose>
            <xsl:when test="position()=1">
              &#10; Prime: 2
              <xsl:next-iteration>
                 <xsl:with-param name="cnt" select="$cnt 1" as="xs:integer"/>
              </xsl:next-iteration>
            </xsl:when>
            <xsl:when test="position() le 5">
              &#10; Prime <xsl:value-of select="."/> Leap: 
              <xsl:value-of select=". - /*//i[$cnt - 1]"/>
              <xsl:next-iteration>
                <xsl:with-param name="cnt" select="$cnt 1" as="xs:integer"/>
              </xsl:next-iteration>
            </xsl:when>
            <xsl:otherwise>
               <xsl:break/>
            </xsl:otherwise>
         </xsl:choose>
      </xsl:iterate>

Not sure whether you need xsl:iterate here.

  • Related