문제

처리된 현재 요소 수를 반영하는 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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top