Sort XSLT by attribute value

I have a question on how to sort based on attribute value.

I have the following source document, and I would like to sort the elements of the track by the value of the title class.

Hope someone can help with this.

<trackList> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Two</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Three</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Four</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Five</title> </track> </trackList> 

The end result should look like this:

 <trackList> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Three</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Five</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Four</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Two</title> </track> </trackList> 

I tried the following, but it does not work.

 <xsl:for-each-group select="title" group-by="@class"> <xsl:for-each select="current-group()"> <xsl:value-of select="@class" /> </xsl:for-each> </xsl:for-each-group> 

Thanks.

+4
source share
1 answer

You can do it as follows:

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="trackList"> <xsl:copy> <xsl:apply-templates select="track"> <xsl:sort select="title/@class"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet> 

When you run on your example input, the result:

 <trackList> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Three</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="SH">Data Five</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Two</title> </track> <track> <location>http://localhost/vmydoc</location> <title class="STD">Data Four</title> </track> </trackList> 
+10
source

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


All Articles