[xsl] Coditional Sort By

Subject: [xsl] Coditional Sort By
From: Jeff Sese <jsese@xxxxxxxxxxxx>
Date: Thu, 24 May 2007 17:31:43 +0800
Hi, I have a XML file like this:

<records>
   <record>
      <field id="130">a field value</field>
      <field id="245">ab field value</field>
      ...
   </record>
   <record>
      <field id="130">ab field value</field>
      <field id="245">ac field value</field>
      ...
   </record>
   <record>
      <field id="245">aa field value</field>
      ...
   </record>
   ...
</records>

I want to sort the record elements using either the field[@id='130'] or field[@id='245'] as sorting key, if one is present. The one with the '130' takes precedence over the one with '245'. If a record has a field[@id='130'] use it as the sort key if there is no field[@id='130'] then use the field[@id='245']; so that the resulting XML would be:

<records>
   <record>
      <field id="130">a field value</field>
      <field id="245">ab field value</field>
      ...
   </record>
   <record>
      <field id="245">aa field value</field>
      ...
   </record>
   <record>
      <field id="130">ab field value</field>
      <field id="245">ac field value</field>
      ...
   </record>
   ...
</records>

Is this possible? I'm thinking of using a variable to hold the possible sort keys of all records then use it as the sort key in my xsl:sort instruction. Something like:

<xsl:variable name="sort.key" as="xs:string+" select="for $i in (/records/record) return if ($i/field[@id='130']) then $i/field[@id='130'] else $i/field[@id='245']"/>

<xsl:template match="records">
   <xsl:apply-templates select="record">
      <xsl:sort select="$sort.key"/>
   </xsl:apply-templates>
</xsl:template>

Thanks,

Jeff

Current Thread