How to get maximum value under same node in xslt

烈酒焚心 提交于 2019-12-04 02:16:21

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>

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

max(*[starts-with(local-name(), 'Hour')])

This XSL:

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

    <!-- Putting the maximum hour from the list into a variable. -->
    <xsl:variable name="max-hour">
      <xsl:call-template name="find-max">
        <!-- Select the list of hour elements you want to look at. -->
        <xsl:with-param name="hours" select="//*[contains(local-name(), 'Hour')]"/>
      </xsl:call-template>
    </xsl:variable>

  <xsl:template match="*">   
    <!-- Displaying the result you are after. -->
    <result>
      <xsl:value-of select="$max-hour"/>
    </result>
  </xsl:template>

  <!-- This template works recursively on the list of hours. -->
  <xsl:template name="find-max">
    <xsl:param name="hours"/>

    <!-- The value of the first hour in this list. -->
    <xsl:variable name="this-hour">
      <xsl:value-of select="$hours[position() = 1]"/>
    </xsl:variable>

    <xsl:choose>
      <xsl:when test="$hours">
        <!-- The maximum value of the remaining hours in this list. -->
        <xsl:variable name="other-hours">
          <xsl:call-template name="find-max">
            <xsl:with-param name="hours" select="$hours[position() != 1]"/>
          </xsl:call-template>
        </xsl:variable>

        <!-- Return the maximum of this hour and the remaining hours. -->
        <xsl:choose>
          <xsl:when test="$other-hours &gt; $this-hour">
            <xsl:value-of select="$other-hours"/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$this-hour"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:when>

      <!-- We've reached the last hour in the list. -->
      <xsl:otherwise/>
    </xsl:choose>

  </xsl:template>

</xsl:stylesheet>

gives you the following output:

<result>51</result>

In XSLT 1 you can use following-sibling

<xsl:value-of select="/Report/Items/Item/*[starts-with(name(), 'Hour')][not(.&lt;following-sibling::*[starts-with(name(), 'Hour')])]"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!