如何使用XSL反转XML歌曲列表 实现最新播放歌曲置顶显示
解决方案
你现有XSL存在重复生成页面结构的问题,同步调整逻辑后即可实现倒序排列要求,修改后的完整XSL代码如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Event"> <html> <body> <ul> <!-- 按StartTime降序排列Song节点 --> <xsl:apply-templates select="Song"> <xsl:sort select="Info/@StartTime" order="descending" data-type="text"/> </xsl:apply-templates> </ul> </body> </html> </xsl:template> <xsl:template match="Song"> <li style="margin-bottom: -10px; margin-left: -30px; list-style: circle;"> <xsl:value-of select="Artist/@name"/> - <xsl:value-of select="@title"/> <span> (<xsl:value-of select="Info/@StartTime"/>) </span> <br /> </li> </xsl:template> </xsl:stylesheet>
核心修改点
- 调整模板结构:将全局的html、body、ul外层标签放到Event节点的匹配模板中,避免每个歌曲节点都重复生成整套页面结构
- 新增排序规则:在应用Song节点模板时,添加
<xsl:sort>配置,以Info/@StartTime为排序依据,设置order="descending"实现播放时间从晚到早倒序 - 简化冗余逻辑:移除了无用的Artist节点匹配模板,直接读取属性值即可完成内容输出,无需嵌套
xsl:for-each循环
修改后输出的列表会将最后播放的歌曲排在最顶部,完全符合需求。
内容的提问来源于stack exchange,提问作者Digi Sol
相关产品推荐
相关产品推荐

