I have a xml as below:
<root>
<row>
<Leave_days>6</Leave_days>
<Maximum>10</Maximum>
<Employee>John</Employee>
</row>
<row>
<Leave_days>4</Leave_days>
<Maximum>15</Maximum>
<Employee>Albert</Employee>
</row>
<row>
<Leave_days>2</Leave_days>
<Maximum>10</Maximum>
<Employee>John</Employee>
</row>
</root>
I need to sum the 'Maximum' but not consider the repeating employee. So for the example above, the output should be 25 (10 for John and 15 for Albert - should ignore the 2nd row for John as it is repeating)
<Root>
<row>25</row>
</Root>
In the below xslt, I'm not sure how to add a condition to eliminate the repeating employee row:
<xsl:template match="root">
<Root>
<row>
<xsl:value-of select="sum(row/Maximum)"/>
</row>
</Root>
</xsl:template>
Also tried with group-by but not able to achieve the result. Please help.
I believe the simplest solution - even in XSLT 2.0 - would be to use the Muenchian grouping expression to select the distinct employee rows:
<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:key name="row-by-emp" match="row" use="Employee" />
<xsl:template match="/root">
<Root>
<row>
<xsl:value-of select="sum(row[count(. | key('row-by-emp', Employee)[1]) = 1]/Maximum)"/>
</row>
</Root>
</xsl:template>
</xsl:stylesheet>
To do this with XSLT 2.0 group-by
you'd need something like:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<xsl:variable name="maxima">
<xsl:for-each-group select="row" group-by="Employee">
<xsl:copy-of select="Maximum"/>
</xsl:for-each-group>
</xsl:variable>
<Root>
<row>
<xsl:value-of select="sum($maxima/Maximum)"/>
</row>
</Root>
</xsl:template>
</xsl:stylesheet>
精彩评论