Xslt如何设置条件奇数/偶数行的样式

mic*_*son 8 xml xslt conditional html-table

我有一个使用xslt转换编写的html表,看起来像这样

<table>
    <xsl:for-each select="someNode">
        <xsl:if test="testThis">
            <tr>
                <!-- <xsl:call-template name="conditionalRowStyle"/> -->
                <td>something</td>
            </tr>
         </xsl:if>
         <tr>
             <!-- <xsl:call-template name="conditionalRowStyle"/> -->
             <td>this is always displayed</td>
         </tr>
         <xsl:if test="testThis2">
            <tr>
                <!-- <xsl:call-template name="conditionalRowStyle"/> -->
                <td>something 2</td>
            </tr>
         </xsl:if>
         ....
    </xsl:for-each>
    <tr>
        <!-- <xsl:call-template name="conditionalRowStyle"/> -->
        <td>this is always displayed</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我需要一种方法来应用不同的类oddRow/evenRow到tr elems.

<tr class="evenRow"> or <tr class="oddRow">
Run Code Online (Sandbox Code Playgroud)

我试着在每个<tr> elem之后使用这样的模板

<xsl:template name="conditionalRowStyle">
    <xsl:attribute name="class">
        <xsl:choose>
            <xsl:when test="(count(../preceding-sibling::tr) mod 2) = 0">oddrow</xsl:when>
            <xsl:otherwise>evenrow</xsl:otherwise>
        </xsl:choose>
    </xsl:attribute>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

但这不起作用.任何的想法?

Kri*_*ris 17

你可能只是css中做到这一点

tr:nth-child(odd) {
    /*...*/
}
tr:nth-child(odd) {
    /*...*/
}
Run Code Online (Sandbox Code Playgroud)

如果你做不到,你可以做点什么

<xsl:attribute name="class">
    <xsl:choose>
        <xsl:when test="(position() mod 2) != 1">
            <xsl:text>evenRow</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>oddRow</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:attribute>
Run Code Online (Sandbox Code Playgroud)

请注意,我在SO文本框中写了这个并没有测试它.