Counter inside xsl:for-each loop

后端 未结 5 721
野性不改
野性不改 2020-12-01 08:49

How to get a counter inside xsl:for-each loop that would reflect the number of current element processed.
For example my source XML is


             


        
相关标签:
5条回答
  • 2020-12-01 09:19

    position(). E.G.:

    <countNo><xsl:value-of select="position()" /></countNo>
    
    0 讨论(0)
  • 2020-12-01 09:24
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
        <xsl:template match="/">
            <newBooks>
                    <xsl:for-each select="books/book">
                            <newBook>
                                    <countNo><xsl:value-of select="position()"/></countNo>
                                    <title>
                                            <xsl:value-of select="title"/>
                                    </title>
                            </newBook>
                    </xsl:for-each>
            </newBooks>
        </xsl:template>
    </xsl:stylesheet>
    
    0 讨论(0)
  • 2020-12-01 09:26

    Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text> in the place of ???.

    Note the "1. " - this is the number format. More info: here

    0 讨论(0)
  • 2020-12-01 09:28

    You can also run conditional statements on the Postion() which can be really helpful in many scenarios.

    for eg.

     <xsl:if test="(position( )) = 1">
         //Show header only once
        </xsl:if>
    
    0 讨论(0)
  • 2020-12-01 09:32

    Try:

    <xsl:value-of select="count(preceding-sibling::*) + 1" />
    

    Edit - had a brain freeze there, position() is more straightforward!

    0 讨论(0)
提交回复
热议问题