[xml] xsl : for-each 루프 내부의 카운터

처리 된 현재 요소의 수를 반영하는 xsl : for-each 루프 내부에서 카운터를 얻는 방법.
예를 들어 내 소스 XML은

<books>
    <book>
        <title>The Unbearable Lightness of Being </title>
    </book>
    <book>
        <title>Narcissus and Goldmund</title>
    </book>
    <book>
        <title>Choke</title>
    </book>
</books>

내가 얻고 싶은 것은 :

<newBooks>
    <newBook>
        <countNo>1</countNo>
        <title>The Unbearable Lightness of Being </title>
    </newBook>
    <newBook>
        <countNo>2</countNo>
        <title>Narcissus and Goldmund</title>
    </newBook>
    <newBook>
        <countNo>3</countNo>
        <title>Choke</title>
    </newBook>
</newBooks>

수정할 XSLT :

<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>???</countNo>
                    <title>
                        <xsl:value-of select="title"/>
                    </title>
                </newBook>
            </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

그래서 질문은 ??? 대신 무엇을 넣어야 하는가입니다. 표준 키워드가 있습니까 아니면 단순히 변수를 선언하고 루프 내에서 증가시켜야합니까?

질문이 꽤 길기 때문에 아마도 한 줄 또는 한 단어 대답을 기대해야합니다. 🙂



답변

position(). 예 :

<countNo><xsl:value-of select="position()" /></countNo>


답변

<xsl:number format="1. "/><xsl:value-of select="."/><xsl:text>??? 대신 삽입 해보십시오 .

“1.”을 참고하십시오. 이것은 숫자 형식입니다. 더 많은 정보 : 여기


답변

시험:

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

편집 -거기에 두뇌가 얼어 붙었을 때 position ()이 더 간단합니다!


답변

Postion ()에서 조건문을 실행할 수도 있는데, 이는 많은 시나리오에서 매우 유용 할 수 있습니다.

예를 들어.

 <xsl:if test="(position( )) = 1">
     //Show header only once
    </xsl:if>


답변

    <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>


답변