johkar
johkar

Reputation: 131

Find node containing the most recent date when date needs converted to valid date format

I need an xPath to be used in a global variable which will select the 'Policy' node with the most recent dateTime (2014-12-02-04:00). Unfortanately the Time delimeter is a dash instead of 'T' so I can't use max() straight away. If I try to use substring or translate to remove the dashes and colon to simply compare numbers I get the error which states that there cannot be more that one sequence in those functions.

Is there a way to evaluate PolicyEffectiveDate from the root node when it is in 2014-12-02-04:00 format?

/Policies/PolicySummary/Policy[2]/PolicyEffectiveDate

XSLT 2.0 is OK. Also, note that I don't have control over the XML format. Thanks.

Given sample XML of:

<?xml version="1.0" encoding="UTF-8"?>
<Policies>
    <PolicySummary>
        <Policy>
            <PolicyNumber>123</PolicyNumber>
            <PolicyEffectiveDate>2014-06-01-04:00</PolicyEffectiveDate>
        </Policy>
        <Policy>
            <PolicyNumber>1234</PolicyNumber>
            <PolicyEffectiveDate>2014-12-02-04:00</PolicyEffectiveDate>
        </Policy>
        <Policy>
            <PolicyNumber>12345</PolicyNumber>
            <PolicyEffectiveDate>2014-08-02-04:00</PolicyEffectiveDate>
        </Policy>
    </PolicySummary>
</Policies>

Upvotes: 0

Views: 112

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

You can simply sort the policies by their "dates" as text. For example:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <xsl:for-each select="Policies/PolicySummary/Policy">
        <xsl:sort select="PolicyEffectiveDate" data-type="text" order="descending"/>
        <xsl:if test="position()=1">
            <xsl:copy-of select="."/>
        </xsl:if>
    </xsl:for-each>
</xsl:template>


</xsl:stylesheet>

will return:

<?xml version="1.0" encoding="utf-8"?>
<Policy>
  <PolicyNumber>1234</PolicyNumber>
  <PolicyEffectiveDate>2014-12-02-04:00</PolicyEffectiveDate>
</Policy>

in your example.

Upvotes: 1

Related Questions