0

I want to sort my xml data and also number them. Here is for example xml code:

  <images>
      <image>
        <title>cat</title>
        <grade>3</grade>
      </image>
      <image>
        <title>dog</title>
        <grade>5</grade>
      </image>
      <image>
        <title>snake</title>
        <grade>1</grade>
      </image>
      <image>
        <title>fish</title>
        <grade>2</grade>
      </image>
   </images>

and xslt code:

  <xsl:template match="images">
    <xsl:for-each select="image">
      <xsl:sort select="grade"/>
      <tr>
        <td>
          <xsl:number/>
        </td>
        <td>
          <xsl:value-of select="title"/>
        </td>
        <td>
          <xsl:value-of select="grade"/>
        </td>
      </tr>
    </xsl:for-each>
  </xsl:template>

The result of this is:

3 cat  1
4 fish 2
1 cat  3
2 dog  5

And i would like to have:

1 cat  1
2 fish 2
3 cat  3
4 dog  5

How can I make this in a simple way?

2 Answers 2

2

Instead of using <xsl:number /> do this instead

 <xsl:value-of select="position()" />

position() will return the position of the node in the selected node-set after it has been sorted (as opposed to the position of the node in the hierarchy).

Sign up to request clarification or add additional context in comments.

Comments

1

xsl:number is good, but you need the current position. Also you should sort by numeric value:

<xsl:template match="images">
    <xsl:for-each select="image">
      <xsl:sort select="number(grade)"/>
      <tr>
        <td>
          <xsl:number value="position()"/>
        </td>
        <td>
          <xsl:value-of select="title"/>
        </td>
        <td>
          <xsl:value-of select="grade"/>
        </td>
      </tr>
    </xsl:for-each>
</xsl:template>

1 Comment

<xsl:sort select="number(grade)"/> That would work in XSLT 2.0, but not in XSLT 1.0. <xsl:sort select="grade" data-type="number"/> would work for both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.