簡體   English   中英

在 XSLT 中排序,僅當 string-length != 0 時

[英]Sorting in XSLT, only when string-length != 0

我使用以下 XSLT 塊從 XML 文件中的“最新”項中獲取描述。 它按日期排序(在我的 XML 中顯示為<date>2011-11-15</date> ),然后從排序列表中選擇頂部。 雖然我剛剛發現有些項目沒有日期,但它們只是像<date/>一樣顯示。 問題是我的 XSLT 將這些放在排序列表的頂部,因此首先選擇沒有日期的項目。

那么,如何按日期對長度大於零的項目進行排序?

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:apply-templates select="/products/product">
      <xsl:sort select="normalize-space(substring(date,0,4))" order="ascending" />
      <xsl:sort select="normalize-space(substring(date,4,2))" order="ascending" />
      <xsl:sort select="normalize-space(substring(date,7,2))" order="ascending" />
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="product">
    <xsl:if test="position()=1">
      <xsl:value-of select="description"/>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

只是避免在排序中包含沒有日期的那些:

<xsl:apply-templates select="/products/product[date]">

順便說一句,(a) 您似乎選擇了列表中最早的項目,而不是最新的項目,並且 (b) 確實沒有必要將日期分成三部分進行格式化:如果所有日期的格式都是 YYYY-MM- DD 那么直接字母排序應該可以完成這項工作,除非系統決定使用奇數整理序列,在這種情況下<xsl:sort select="number(translate(date, '-', ''))" data-type="number"/>可能更安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM