programing

counter inside xsloop

codeshow 2023. 10. 19. 22:52
반응형

counter inside xsloop

처리된 현재 요소의 수를 반영하는 각 루프에 대해 xsl 내부의 카운터를 가져오는 방법.
예를 들어 나의 소스 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" />

편집 - 뇌가 얼어붙었다면 위치()가 더 간단합니다!

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

언급URL : https://stackoverflow.com/questions/93511/counter-inside-xslfor-each-loop

반응형