[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

RE: [xsl] Find the node with maximum elements


Subject: RE: [xsl] Find the node with maximum elements
From: "Scott Trenda" <Scott.Trenda@xxxxxxxx>
Date: Mon, 5 Nov 2007 10:00:33 -0600

This may be better represented with 2.0's grouping facilities, but
here's the 1.0 solution I'd use to alleviate Mukul's concerns (building
off Michael's response with <xsl:sort/>):

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:key name="cars" match="*[Car]" use="count(Car)"/>

  <xsl:template match="Sample">

    <xsl:variable name="max-cars">
      <xsl:for-each select=".//*[Car]">
        <xsl:sort select="count(Car)" data-type="number"/>
        <xsl:if test="position() = last()">
          <xsl:value-of select="count(Car)"/>
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>

    <xsl:for-each select="key('cars', $max-cars)">
      <!-- do whatever you'd do with the results here -->
      <xsl:value-of select="name()"/>
    </xsl:for-each>

  </xsl:template>

</xsl:stylesheet>

~ Scott


-----Original Message-----
From: Mukul Gandhi [mailto:gandhi.mukul@xxxxxxxxx]
Sent: Sunday, November 04, 2007 1:33 AM
To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
Subject: Re: [xsl] Find the node with maximum elements

Hi Mike,
   IMHO, there seems to be a slight flaw in this logic. This program
will return only the last instance (i.e. only 1) of the maximum, and
not all maximum instances.

I think, Ken's answer meets exactly the OP's requirements.

On 11/4/07, Michael Kay <mike@xxxxxxxxxxxx> wrote:
> Easiest (even in 2.0) is to sort elements according to the number of
> children and take the last:
>
> <xsl:for-each select="Sample/*">
>  <xsl:sort select="count(child::*)" data-type="number"/>
>  <xsl:if test="position()=last()">
>    <xsl:value-of select="name()"/>
>  </
> </
>
> Michael Kay
> http://www.saxonica.com/
>
> > -----Original Message-----
> > From: Avaneesh Ramprasad [mailto:avaneesh@xxxxxxxxxxxxxx]
> > Sent: 03 November 2007 19:05
> > To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
> > Subject: [xsl] Find the node with maximum elements
> >
> > Hello,
> > I have a requirement to write a xsl transformation to find
> > the node which has the maximum number of elements
> >
> > Below is a sample xml file
> >
> > <Sample>
> >     <Toyota>
> >           <Car>Camry</Car>
> >           <Car>Corrola</Car>
> >      </Toyota>
> >      <Honda>
> >             <Car>Accord></Car>
> >           <Car>Civic</Car>
> >           <Car>Pilot</Car>
> >      </Honda>
> >      <Mitsubishi>
> >         <Car>Lancer</Car>
> >         <Car>Lancer</Car>
> >         <Car>Lancer</Car>
> >      </Mitsubishi>
> >     <Hyundai>
> >         <Car>Sonata</Car>
> >         <Car>Accent</Car>
> > </Hyundai>
> > </Sample>
> >
> > The xsl should return Honda and Mitsubishi
> >
> > Would appreciate your help.
> >
> > Thanks
> > Avaneesh


--
Regards,
Mukul Gandhi


Current Thread
Keywords