XSLT2选择组的子集

时间:2016-08-30 18:34:31

标签: xml xslt xpath

我对使用组有些新意,并希望能够使用position()选择teh组的子集。

我已经根据需要使用此代码(根据需要创建组和正确的输出。)

    

<xsl:template match="Locations">
    <table>
        <tbody>
        <xsl:for-each-group select="Location" group-by="Country">
            <xsl:sort data-type="text" order="ascending" select="."/>
            <xsl:for-each-group select="current-group()" group-by="current-grouping-key()">
            </xsl:for-each-group>
            <tr>
                <td class="country"><xsl:value-of select="current-grouping-key()"/></td>
            </tr>
            <xsl:for-each-group select="current-group()" group-by="City">
                <xsl:sort data-type="text" order="ascending" select="current-grouping-key()"/>
                <tr>
                    <td class="city"><xsl:value-of select="fn:current-grouping-key()"/></td>
                </tr>
            </xsl:for-each-group>
        </xsl:for-each-group>
        </tbody>
    </table>
</xsl:template>

如果我想获得第2到第4个国家/地区标签,我将如何进行此操作?我尝试了position(),但没有得到一个数字,而是获得了分组键值,例如CA.

这是源XML:

<Locations> <Location> <Country>US</Country> <City>New York</City> </Location> <Location> <Country>US</Country> <City>Houston</City> </Location> <Location> <Country>MX</Country> <City>Cancun</City> </Location> <Location> <Country>CH</Country> <City>Zurich</City> </Location> <Location> <Country>CA</Country> <City>Toronto</City> </Location> <Location> <Country>DE</Country> <City>Berlin</City> </Location> <Location> <Country>JP</Country> <City>Tokyo</City> </Location> <Location> <Country>GB</Country> <City>London</City> </Location> <Location> <Country>CA</Country> <City>Edmonton</City> </Location> </Locations>

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

  

如果我想获得第2到第4个国家/地区标签,我该怎么做?   那样做呢?

我想你会这样做:

<xsl:template match="Locations">
    <table border="1">
        <tbody>
            <xsl:for-each-group select="Location" group-by="Country">
                <xsl:sort select="." data-type="text" order="ascending"/>
                <xsl:if test="position() ge 2 and position() le 4">
                    <tr>
                        <td class="country">
                            <xsl:value-of select="current-grouping-key()"/>
                        </td>
                    </tr>
                    <xsl:for-each-group select="current-group()" group-by="City">
                        <xsl:sort select="." data-type="text" order="ascending"/>
                        <tr>
                            <td class="city">
                                <xsl:value-of select="current-grouping-key()"/>
                            </td>
                        </tr>
                    </xsl:for-each-group>
                </xsl:if>
            </xsl:for-each-group>
        </tbody>
    </table>
</xsl:template>