Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 874
CodeGuru Avatar asked Jul 31 '13 06:07

CodeGuru


People also ask

How do I find the maximum value in XSLT?

math:max() returns the maximum value of a node-set. To compute the maximum value of the node-set, the node set is sorted into descending order as it would be using xsl:sort() with a data type of number . The maximum value is then the first node in the sorted list, converted into a number.

How do you write greater than or equal to in XSLT?

<xsl:if test="count(zone) &gt;= 2"> This is a boolean expression because it uses the greater-than-or-equal boolean operator. If the count() function returns a value greater than or equal to 2, the test attribute is true . Otherwise, the test attribute is false .

What is current group () in XSLT?

Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*

What is Number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit)


2 Answers

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>
like image 163
Martin Honnen Avatar answered Oct 22 '22 15:10

Martin Honnen


In XSLT 2.0, with Item as the context node, use

max(*[starts-with(local-name(), 'Hour')])
like image 4
Michael Kay Avatar answered Oct 22 '22 15:10

Michael Kay