How to sort a sorted list in XSLT

I used xsl: sorting in apply-templates to sort the elements, and I would like them to be numbered as well, but if I try to use xsl: number, it just gives the starting position, not after sorting. I think variables cannot be used either because they cannot be changed? So how can I list my list correctly?

+3
source share
2 answers

You can use <xsl:value-of select="position()" />to get the current position in the loop.

From the xpath specification: The position function returns a number equal to the position of the context from the evaluation context of the expression .

XML:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<library>
  <book><name>abc</name></book>
  <book><name>def</name></book>
  <book><name>aaa</name></book>
</library>

XSLT (test.xsl):

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <xsl:for-each select="/library/book">
      <xsl:sort select="name" data-type="text" />
      <xsl:value-of select="position()" />: <xsl:value-of select="name" />, 
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
+1
source

OP:

, ! ! for-each, <xsl:apply-templates select="book">.

, <xsl:apply-templates> - not <xsl:for-each>:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:apply-templates>
   <xsl:sort select=". mod 3"/>
  </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="num">
  <xsl:text>&#xA;</xsl:text>
  <xsl:value-of select="position()"/>: <xsl:text/>
  <xsl:copy-of select="."/>
 </xsl:template>
</xsl:stylesheet>

XML:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

, 3:

1: <num>03</num>
2: <num>06</num>
3: <num>09</num>
4: <num>01</num>
5: <num>04</num>
6: <num>07</num>
7: <num>10</num>
8: <num>02</num>
9: <num>05</num>
10: <num>08</num>

- , XSLT 1.0:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
  <numsMax>
   <xsl:apply-templates>
    <xsl:sort data-type="number" order="descending"/>
   </xsl:apply-templates>
  </numsMax>
 </xsl:template>

 <xsl:template match="num">
  <xsl:if test="position()=1">
   <xsl:copy-of select="."/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

XML:

<nums>
  <num>07</num>
  <num>10</num>
  <num>05</num>
  <num>02</num>
  <num>03</num>
  <num>08</num>
  <num>04</num>
  <num>01</num>
  <num>06</num>
  <num>09</num>
</nums>

, position()=1 node -list:

<numsMax>
   <num>10</num>
</numsMax>
+1

Source: https://habr.com/ru/post/1796559/


All Articles