Akhilesh Perla
Akhilesh Perla

Reputation: 3

Sort XML to XML using XSLT transformer

I have an xml like this

<?xml version="1.0" encoding="UTF-8"?> 
<MANAGER_HIERARCHY> 
  <tables>
    <II_OUTPUT>
      <row id="0">
        <LNAME>Gola</LNAME> 
      </row> 
      <row id="1">
        <LNAME>Chaganti</LNAME>
      </row>
    </II_OUTPUT>
  </tables>
</MANAGER_HIERARCHY>

I would like to sort the xml based on LNAME and i'm expecting the below output

<?xml version="1.0" encoding="UTF-8"?>
<MANAGER_HIERARCHY>
  <tables>
    <II_OUTPUT>
      <row id="0">
        <LNAME>Chaganti</LNAME>
      </row>
      <row id="1">
       <LNAME>Gola</LNAME>
      </row>
    </II_OUTPUT>
  </tables>
</MANAGER_HIERARCHY>

I have written an XSLT to do the same but i'm unable to sort.Please suggest me the write XSLT code to acheive my requirement.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="urn:Test.Namespace">
  <xsl:output indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="text()[not(string-length(normalize-space()))]"/>

  <xsl:template match="/">
    <xsl:apply-templates/>
    <xsl:apply-templates select="MANAGER_HIERARCHY/tables/row">
      <xsl:sort select="*/LNAME" />
    </xsl:apply-templates>
  </xsl:template>

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

Upvotes: 0

Views: 751

Answers (1)

Tim C
Tim C

Reputation: 70598

You are trying to sort row elements, which are child nodes of II_OUTPUT. This means you just need a template matching II_OUTPUT in which you copy it, then select the child row elements in the order you need.

<xsl:template match="II_OUTPUT">
  <xsl:copy>
    <xsl:apply-templates select="row">
      <xsl:sort select="LNAME" />
    </xsl:apply-templates>
  </xsl:copy>
</xsl:template>

The identity template, which you have included, then takes care of everything else.

Try this XSLT

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

  <xsl:template match="text()[not(string-length(normalize-space()))]"/>

  <xsl:template match="II_OUTPUT">
    <xsl:copy>
      <xsl:apply-templates select="row">
        <xsl:sort select="LNAME" />
      </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: 1

Related Questions