如果没有for-each,如何排序数据

时间:2018-12-19 22:12:52

标签: xslt

考虑以下输入XML:

http://prometheus:9090

下面的示例显示了艺术家使用<catalog> <cd> <artist>Dolly Parton</artist> <year>1982</year> </cd> <cd> <artist>Christians</artist> <year>2005</year> </cd> <cd> <artist>Bonnie Tyler</artist> <year>1982</year> </cd> <cd> <artist>Abba</artist> <year>2001</year> </cd> </catalog>

排序的数据
<xsl:sort>

我似乎无法弄清楚的是,如果XSL不包含显式的 <table border="1"> <tr bgcolor="#9acd32"> <th style="text-align:left">Artist</th> <th style="text-align:left">Year</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:sort select="artist" /> <tr> <td><xsl:value-of select="artist"/></td> <td><xsl:value-of select="year"/></td> </tr> </xsl:for-each> </table> ,那么如何对数据进行排序,但是循环由<xsl:for-each处理,如下所示例。 我已经尝试过在<xsl:apply-templates行下使用<xsl:sort,但这给了我一个错误<xsl:template match

element sort is not allowed within that context

1 个答案:

答案 0 :(得分:2)

xsl:sort元素可以是xsl:for-eachxsl:apply-templates的子元素。

示例:

XSLT 1.0

<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="/catalog">
    <output>
        <xsl:apply-templates select="cd[year=1982]">
             <xsl:sort select="artist" />
        </xsl:apply-templates>
    </output>
</xsl:template>

<xsl:template match="cd">
    <artist>
        <xsl:value-of select="artist"/>
    </artist>
</xsl:template>

</xsl:stylesheet>

应用于您的输入示例,结果将是:

<?xml version="1.0" encoding="UTF-8"?>
<output>
  <artist>Bonnie Tyler</artist>
  <artist>Dolly Parton</artist>
</output>