xmlxsltxslt-1.0xslt-2.0

How to get maximum value under same node in xslt


I have a xml like below :

<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>HourlyReport</Name>
  <Id>8</Id>
  <TotalResults>1</TotalResults>
  <TotalPages>1</TotalPages>
  <Items>
    <Item>
      <Id>1</Id>
      <Hour0>23</Hour0>
      <Hour1>12</Hour1>
      <Hour2>7</Hour2>
      <Hour3>18</Hour3>
      <Hour4>32</Hour4>
      .
      .
      .
      <Hour20>28</Hour20>
      <Hour21>39</Hour21>
      <Hour22>51</Hour22>
      <Hour23>49</Hour23>
    </Item>
  </Items>
</Report>

i Need maximum value from above XML using xslt . In above case maximum value is 51. How i can get that? Also is it possible to get this maximum value in any xslt variable, so i can use it some where else. I am not getting any way. You can use any xslt version 1.0 or 2.0 .


Solution

  • Given XSLT 2.0 it should suffice to use

    <xsl:variable name="max" select="max(/Report/Items/Item/*[starts-with(local-name(), 'Hour')]/xs:integer(.)"/>
    

    (where the stylesheet would need to declare xmlns:xs="http://www.w3.org/2001/XMLSchema").

    And with XSLT 1.0 I would simply sort and take the maximum value as in

    <xsl:variable name="max">
      <xsl:for-each select="/Report/Items/Item/*[starts-with(local-name(), 'Hour')]">
        <xsl:sort select="." data-type="number" order="descending"/>
        <xsl:if test="position() = 1"><xsl:value-of select="."/></xsl:if>
      </xsl:for-each>
    </xsl:variable>