How to find min and max value using xsl 1.0?
14,647
Sort and then takes the first for the minimum and the last item for the maximum:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="data-url" select="'file_1.xml'"/>
<xsl:variable name="data-doc" select="document($data-url)"/>
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:key name="k1" match="items" use="item"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="items">
<xsl:variable name="this" select="."/>
<xsl:copy>
<xsl:copy-of select="item"/>
<xsl:for-each select="$data-doc">
<xsl:for-each select="key('k1', $this/item)">
<xsl:sort select="price" data-type="number" order="ascending"/>
<xsl:if test="position() = 1">
<min>
<xsl:value-of select="price"/>
</min>
</xsl:if>
<xsl:if test="position() = last()">
<max>
<xsl:value-of select="price"/>
</max>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
When I apply above stylesheet with Saxon 6.5.5 on the input document
<productlist>
<items>
<item>Pen</item>
</items>
<items>
<item>Bag</item>
</items>
</productlist>
where the other file is
<productlist>
<items>
<item>Pen</item>
<price>8</price>
</items>
<items>
<item>Pen</item>
<price>5</price>
</items>
<items>
<item>Pen</item>
<price>10</price>
</items>
<items>
<item>Bag</item>
<price>15</price>
</items>
<items>
<item>Bag</item>
<price>22</price>
</items>
<items>
<item>Bag</item>
<price>20</price>
</items>
</productlist>
I get the wanted result
<productlist>
<items>
<item>Pen</item>
<min>5</min>
<max>10</max>
</items>
<items>
<item>Bag</item>
<min>15</min>
<max>22</max>
</items>
</productlist>
Author by
user475464
Updated on August 21, 2022Comments
-
user475464 over 1 year
file_1.xml
<productlist> <items> <item>Pen</item> <price>8</item> </items> <items> <item>Pen</item> <price>5</item> </items> <items> <item>Pen</item> <price>10</item> </items> <items> <item>Bag</item> <price>15</item> </items> <items> <item>Bag</item> <price>22</item> </items> <items> <item>Bag</item> <price>20</item> </items> </productlist>
file_2.xml
<productlist> <items> <item>Pen</item> </items> <items> <item>Bag</item> </items> </productlist>
need out put like below with max and min value using xsl 1.0
<productlist> <items> <item>Pen</item> <min>5</min> <max>10</max> </items> <items> <item>Bag</item> <min>15</min> <max>22</max> </items> </productlist>
-
C. M. Sperberg-McQueen over 11 yearsNice. If only the OP had not asked explicitly for XSLT 1.0!