Link to home
Start Free TrialLog in
Avatar of sri1209
sri1209

asked on

Manipulate the sequence of tags in xml with xsl

Hi,

i need to change the sequence of the xml tag , below is the current  xml

<Summary>
    <Category type="CA">
    <Description>You no longer qualify for CA</Description>
    </Category>
    <Category type="FF">
      <Description>You no longer qualify for FF</Description>
    </Category>
    <Category type="MM">
     <Description>You no longer qualify </Description>
    </Category>
    <Category type="CC">
   <Description>Based on information you provided </Description>
    </Category>
  </Summary>

i always need FF first, then CA, CC and MM in the order.. is there a way to do this in xslt.

<Summary>
    <Category type="FF">
      <Description>You no longer qualify for FF</Description>
    </Category>
    <Category type="CA">
    <Description>You no longer qualify for CA</Description>
    </Category>
   <Category type="CC">
   <Description>Based on information you provided </Description>
    </Category>
    <Category type="MM">
     <Description>You no longer qualify </Description>
    </Category>
 
  </Summary>
 

Thank you
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

The brute force approach in XSLT1

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    
    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>
      
    <xsl:template match="node()">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="Summary">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="Category[@type = 'FF']"/>
            <xsl:apply-templates select="Category[@type = 'CA']"/>
            <xsl:apply-templates select="Category[@type = 'CC']"/>
            <xsl:apply-templates select="Category[@type = 'MM']"/>
        </xsl:copy>
    </xsl:template>
    
</xsl:stylesheet>

Open in new window

A more refined technique in XSLT1 is described here
https://www.experts-exchange.com/questions/21571844/Irregular-or-user-defined-sort-order.html
I like the elegance of my approach there, but it requires the document() function to be switched on
If you are using XSLT2, it is easy, just make a sequence of the four terms and use index-of or a function in the @select of the sort
Let me know if you like a XSLT2 solution
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sri1209
sri1209

ASKER

Hi Geert,

Sorry for the delay in replying back, you are awesome, works perfectly.