NiTiN
NiTiN

Reputation: 1022

XSLT: Sort based on child node's attribute

I want to sort parent node, based on child's name attribute.

XML unsorted:

<grand-parent>
  <parent>
    <child name="c"/>
    <child_next name="a"/>
  </parent>
  <parent>
    <child name="a"/>
    <child_next name="a"/>
  </parent>
  <parent>
    <child name="b"/>
    <child_next name="a"/>
  </parent>
</grand-parent>

Expected Output:

<grand-parent>
  <parent>
    <child name="a"/>
    <child_next name="a"/>
  </parent>
  <parent>
    <child name="b"/>
    <child_next name="a"/>
  </parent>
  <parent>
    <child name="c"/>
    <child_next name="a"/>
  </parent>
</grand-parent>

XSLT In Use (not working - returns the same XML that is input):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes" method="xml" encoding="UTF-8"/>
  <xsl:strip-space  elements="*"/>
  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*">
        <xsl:sort select="/grand-parent/parent/child/@name" order="descending" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>  
</xsl:stylesheet>

Upvotes: 1

Views: 4428

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52858

I would take the sort out of the identity transform:

XSLT 1.0

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

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

    <xsl:template match="grand-parent">
        <xsl:copy>
            <xsl:apply-templates select="parent|@*">
                <xsl:sort select="child/@name" data-type="text"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Output

<grand-parent>
   <parent>
      <child name="a"/>
      <child_next name="a"/>
   </parent>
   <parent>
      <child name="b"/>
      <child_next name="a"/>
   </parent>
   <parent>
      <child name="c"/>
      <child_next name="a"/>
   </parent>
</grand-parent>

Upvotes: 4

Related Questions