pdf
pdf

Reputation: 21

Extracting the "oldest" date from XML data in XSLT 1.0

again fighting with the XSLT 1.0. This time I have the following scenario. I have some data, and for each I have an assigned date. I am able to print them sorted, but due to my small knowledge of XSLT, it's not what I want. I do not want to get the full output from the XML, I want to get just the most recent or the oldest in term of date.

the date format is "dd/mm/yyyy".

For example with the following XML:

<PICNews>

 <news>

    <Date>31/06/2007</Date>
    <Author>Dan Jurden</Author>
    <Type>Memo</Type>
    <Text>This is a memo.</Text>
</news>
<news>
    <Date>21/07/2007</Date>
    <Author>Dan Jurden</Author>
    <Type>News</Type>
    <Text>This is some news.</Text>
</news>
<news>
    <Date>22/06/2007</Date>
    <Author>Dan Jurden</Author>
    <Type>Alert</Type>
    <Text>This is an alert.</Text>
</news>

I would like to find a transformation that will give me back the 22/06/2007 and the 21/07/2007.

The following XSLT code (just a snippet) will print the data as ordered list, I want to get only the first or last:

<xsl:for-each select="/PICNews/news">
    <xsl:sort select="substring(./Date,7,10)" order="descending"/> 
    <xsl:sort select="substring(./Date,4,6)" order="descending"/> 
    <xsl:sort select="substring(./Date,1,2)" order="descending"/> 
    Date = <xsl:value-of select="./Date" />  <br/>
</xsl:for-each>

I am looking for a solution like:

<xsl:apply-templates select="OldestDate"/>

that should give me 22/06/2007

Any suggestion?

Upvotes: 1

Views: 395

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167696

Inside of the for-each you can check <xsl:if test="position() = 1"> respectively position() = last() to find the first respectively last in sort order.

Upvotes: 0

michael.hor257k
michael.hor257k

Reputation: 117073

I want to get only the first or last:

To get the first (i.e. earliest) date, try:

<xsl:for-each select="/PICNews/news">
    <xsl:sort select="substring(Date,7,4)" data-type="number" order="ascending"/>
    <xsl:sort select="substring(Date,4,2)" data-type="number" order="ascending"/>
    <xsl:sort select="substring(Date,1,2)" data-type="number" order="ascending"/>
    <xsl:if test="position()=1">
         Date = <xsl:value-of select="Date" />  <br/>
    </xsl:if>
</xsl:for-each>

To get the last (i.e. latest) date, change:

<xsl:if test="position()=1">

to:

<xsl:if test="position()=last()">

P.S. Note the differences in the substring() calls and the sort data-type.

Upvotes: 1

Related Questions