purum
purum

Reputation: 323

xsl: sort nodes by values of subnode

Is it possible to sort the following xml with xsl (sort SubGroup in Group by date in mm/dd/yyyy format):

<Data version="2.0">
   <Group>
        <SubGroup>          
            <Date>11/14/2011</Date>
        </SubGroup>
        <SubGroup>          
            <Date>10/25/2011</Date>
        </SubGroup>
   </Group>
   <Group>
        <SubGroup>
            <Date>01/14/2008</Date>
        </SubGroup>
        <SubGroup>          
            <Date>11/01/2005</Date>
        </SubGroup>
   </Group>
</Data>

to this one:

<Data version="2.0">
   <Group>
        <SubGroup>
            <Date>10/25/2011</Date>
        </SubGroup>
        <SubGroup>          
            <Date>11/14/2011</Date>
        </SubGroup>
   </Group>
   <Group>
        <SubGroup>
            <Date>11/01/2005</Date>
        </SubGroup>
        <SubGroup>          
            <Date>01/14/2008</Date>
        </SubGroup>
   </Group>
</Data>

As I think there are two tasks: 1) sorting SubGroups by values in inner node 2) Sorting by date in special format. Please post an answer if you know how to solve the (1) problem for sorting by integer values instead of date.

Upvotes: 3

Views: 2041

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

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

  <xsl:template match="Group">
    <xsl:copy>
      <xsl:apply-templates select="SubGroup">
        <xsl:sort select="concat(
                  substring(Date, 7, 4),
                  substring(Date, 1, 2),
                  substring(Date, 4, 2)
                  )"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 3

Related Questions