Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognize first loop run in XSLT

I am pretty new to XSLT and might be looking at my problem from the wrong angle - coming from languages such as C++ and Java. I hope someone can help me out.

I want to make a loop call (xsl:for-each) in XSLT and do something specific on the first run through the loop. In other languages I would use a status variable for this, but variables cannot change their value in XSLT as I have learned, so how can I solve this problem? Here is what I want to do. The upper case part in the if clause is of course fake and represents my problem.

<xsl:for-each select="browser/value">  <xsl:if test="FIRST TIME IN LOOP">   do something once  </xsl:if>   <xsl:value-of select="current()" /> </xsl:for-each> 

Thanks alot! Henrik

like image 295
Henrik Avatar asked Apr 25 '12 15:04

Henrik


People also ask

How do you run a loop in XSLT?

You can format your XSLT stylesheet to go to a specific node, and then loop through the given node set. You create an XSLT loop with the <xsl:for-each> tag. The value of the select attribute in this tag is an XPath expression that allows you to specify the data element to loop through.

What is XSLT 3. 0?

XSLT 3.0 allows XML streaming which is useful for processing documents too large to fit in memory or when transformations are chained in XML Pipelines. Packages, to improve the modularity of large stylesheets. Improved handling of dynamic errors with, for example, an xsl:try instruction.

How do you break out of a loop in XSLT?

There is no such a thing as break in an XSLT for-each loop. xsl:if/@test is pretty much all you can do. The other way would be to include this condition within the for-each/@select.

How to iterate array in XSLT?

Anyway, for a start, I would suggest to use <xsl:variable name="listData" select="met:getData($Id)"/> , that is all you can do on the XSLT side to bind the variable to the result from the function call, your current attempt makes the variable hold a tree fragment containing a text node with the string value of the ...


1 Answers

I think the easiest way is to check the position of the current node. It's also faster than checking the existence of preceding value elements in the tree (and will still work if xsl:sort is added to the loop):

<xsl:for-each select="browser/value">   <xsl:if test="position()=1">     do something here   </xsl:if>   <xsl:value-of select="blah"/> </xsl:for-each> 
like image 56
Martin Avatar answered Sep 21 '22 18:09

Martin