首页 > 解决方案 > XSL 将特定值排序到最后

问题描述

是否可以按如下方式对节点进行排序:

示例 XML

<record>
   <id>0</id>
   <sku>0</sku>
   <name>Title</name>
   <prop>456</prop>
   <number>99</number>
</record>

如果我应用这个模板

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
     <xsl:template match="record/*">
     <xsl:param select="." name="value"/>
        <div>
           <xsl:value-of select="concat(local-name(), ' - ', $value)"/>
         </div>
     </xsl:template>
</xsl:stylesheet>

输出:

<div>id - 0</div>
<div>sku - 0</div>
<div>name - Title</div>
<div>prop - 456</div>
<div>number - 99</div>

但是,我希望最后输出所有 0 值,如下所示:

<div>name - Title</div>
<div>prop - 456</div>
<div>number - 99</div>
<div>id - 0</div>
<div>sku - 0</div>

这可以通过对 应用排序来实现<xsl:apply-templates/>吗?

标签: xsltxslt-1.0

解决方案


使用 XSLT-1.0 有一种简单的方法可以实现这一点。只需使用谓词xsl:apply-templates检查内容是否为零:

 <xsl:template match="record/*">
    <div>
       <xsl:value-of select="concat(local-name(), ' - ', .)"/>
     </div>
 </xsl:template>

 <xsl:template match="/record">
    <xsl:apply-templates select="*[normalize-space(.) != '0']" />
    <xsl:apply-templates select="*[normalize-space(.)  = '0']" />
 </xsl:template>

这不会对输出进行排序,而是按照您想要的方式对其进行分组。xsl:param是不必要的。


推荐阅读