How to check whether the XSLT statement has been executed


I have a for-each statement in my XSLT and an if condition inside it. I need to execute a piece of statement just first time when the if condition is true.

<xsl:for-each select="">
    <!-- if condition true -->
        <!-- DO SOMETHING -->
        <!-- if its the first entry in the if condition do something -->
    <!-- End If -->

I am not able to use any variables to set the value to true false, since variables are constants in XSLT. Is there any way to achieve this?

You're thinking too procedurally. In XSLT, it helps to think declaratively instead. Rather than trying to set a flag, test a condition against the input document.

For example, in your case, you can test the position of the item,

    <xsl:if test="position() = 1">

rather than set a flag.

You might further consider whether looping via for-each is the best way to achieve your objective; often, apply-templates works better to invoke relevant templates that match nodes in the input document.

Update: You can move condition into the select and still use position() = 1 if you want the first position test to apply only to the first case where condition applies.

<xsl:for-each select="original_select_AND_CONDITION">
    <!-- do something for all cases -->
    <xsl:if test="position() = 1">
        <!-- do something for first case -->