Re: [xsl] What is the simplest method for using xsl:sort without losing attribute names and values?

Subject: Re: [xsl] What is the simplest method for using xsl:sort without losing attribute names and values?
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Sun, 20 Jul 2008 12:59:42 +0200
Mark Wilson wrote:

I want to do a simple sort without losing either elements or attributes. The xls style sheet I have written works, but there must be a more
succinct method. One element <Cat> has four attributes (two optional), the other <Person> has one optional attribute. When the templates for <Cat> and <Person> are not present in my style sheet, I lose the attributes but not the elements themselves.

If you want to copy everything but also want to make some changes then you usually start with a template for the identity transformation
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
then you add templates for the changes. Thus if you want process the child elements of an element sorted on Year, IssueNumber, Page, as the template below suggests


   <xsl:template match="*">
       <xsl:copy>
           <xsl:apply-templates>
               <xsl:sort select="Year" />
               <xsl:sort select="IssueNumber"/>
               <xsl:sort select="Page" />
           </xsl:apply-templates>
       </xsl:copy>
   </xsl:template>

then you need to make sure you process attributes as well:


   <xsl:template match="*">
       <xsl:copy>
           <xsl:apply-templates select="@*"/>
           <xsl:apply-templates>
               <xsl:sort select="Year" />
               <xsl:sort select="IssueNumber"/>
               <xsl:sort select="Page" />
           </xsl:apply-templates>
       </xsl:copy>
   </xsl:template>

On the other hand you probably don't want to sort for all elements that way so I would rather expect something like

   <xsl:template match="foo">
       <xsl:copy>
           <xsl:apply-templates select="@*"/>
           <xsl:apply-templates>
               <xsl:sort select="Year" />
               <xsl:sort select="IssueNumber"/>
               <xsl:sort select="Page" />
           </xsl:apply-templates>
       </xsl:copy>
   </xsl:template>

to suffice, where foo is the name of the element whose children you want to process sorted.


--


	Martin Honnen
	http://JavaScript.FAQTs.com/

Current Thread