Ignoring 'A' and 'The' when sorting with XSLT

后端 未结 2 425
生来不讨喜
生来不讨喜 2020-12-21 08:29

I would like to have a list sorted ignoring any initial definite/indefinite articles \'the\' and \'a\'. For instance:

  • The Comedy of Errors
  • Hamlet
相关标签:
2条回答
  • 2020-12-21 09:14

    This transformation:

    <xsl:template match="plays">
     <p>Plays sorted by title: </p>
        <xsl:for-each select="play">
          <xsl:sort select=
          "concat(@title
                   [not(starts-with(.,'A ') 
                      or 
                       starts-with(.,'The '))],
                  substring-after(@title[starts-with(., 'The ')], 'The '),
                  substring-after(@title[starts-with(., 'A ')], 'A ')
                  )
         "/>
          <p>
            <xsl:value-of select="@title"/>
          </p>
        </xsl:for-each>
    </xsl:template>
    

    when applied on this XML document:

    produces the wanted, correct result:

    <p>Plays sorted by title: </p>
    <p>Barber</p>
    <p>The Comedy of Errors</p>
    <p>CTA &amp; Fred</p>
    <p>Hamlet</p>
    <p>A Midsummer Night's Dream</p>
    <p>Twelfth Night</p>
    <p>The Winter's Tale</p>
    
    0 讨论(0)
  • 2020-12-21 09:22

    Here is how I would do that:

    <xsl:template match="plays">
        <xsl:for-each select="play">
          <xsl:sort select="substring(title, 1 + 2*starts-with(title, 'A ') + 4*starts-with(title, 'The '))"/>
          <p>
            <xsl:value-of select="title"/>
          </p>
        </xsl:for-each>
    </xsl:template>
    

    Update: I forgot to add 1 to the expression (classic off-by-one error)

    Well, starts-with is from XSLT 1.0. Prooflink: the first search result in Google yields XSLT 1.0: function starts-with

    0 讨论(0)
提交回复
热议问题