Highest value for each group in XSL

This is probably a very simple solution to this problem. I could easily do this in C # -LINQ. Unfortunately, I am not so experienced with XPath and XSL.

I have an input XML file that contains the following structure:

<group>
    <val>1</val>
    <val>3</val>
    <val>1</val>
</group>
<group>
    <val>3</val>
    <val>2</val>
    <val>2</val>
</group>

Now in my XSL transform I want to define 1 variable "highsum" that contains the highest sum of "values". Thus, for example, it will return 7, the sum of all the values ​​in the second group.

After some searching, this is the closest solution I found:

http://w3schools.invisionzone.com/index.php?showtopic=24265

But I have a feeling that there is a better way than using sorting in a template to achieve this result. Any members?

+3
1

I. XSLT 1.0 (, ):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/*">
   <xsl:for-each select="group">
     <xsl:sort select="sum(val)" data-type="number"
      order="descending"/>

     <xsl:if test="position()=1">
       <xsl:value-of select="sum(val)"/>
     </xsl:if>
   </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

, XML-:

<t>
    <group>
        <val>1</val>
        <val>3</val>
        <val>1</val>
    </group>
    <group>
        <val>3</val>
        <val>2</val>
        <val>2</val>
    </group>
</t>

, :

7

, <xsl:for-each> .

II. XSLT 2.0 ( XPath 2.0 ):

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/*">
   <xsl:sequence select="max(group/sum(val))"/>
 </xsl:template>
</xsl:stylesheet>

, XML-, :

7

:

  <xsl:variable name="vHighestSum" 
       select="max(group/sum(val))"/>

, Xpath XQuery :

let $vHighestSum := max(/*/group/sum(val))
+3

Source: https://habr.com/ru/post/1757580/


All Articles