I made a list of books in XML. The following is the format of my XML file; there are some more <book> blocks, of course.
<data>
<book>
<title>Encyclopaedia Britannica</title>
<category>encyclopedia</category>
<language>English</language>
<author>Encyclopaedia Britannica Editorial</author>
<year>1768</year>
<price>49.99</price>
</book>
</data>
And I want to print the title of the most expensive one. I tried as follows in the .xsl file:
<p style = "display: block;">
The most expensive book is "
<xsl:for-each select="data/book">
<xsl:sort select="price" order="descending"/>
<!-- <xsl:value-of select="title"/> -->
</xsl:for-each>
<xsl:value-of select="data/book/title"/>
"
</p>
When the <xsl:value-of> block in <xsl:for-each>(which I set as comment) is executed it prints all the books sorted in descending order. Of course, <xsl:value-of select="data/book/title"/> makes the first book of the original table get printed.
So I want to print the most expensive one by stopping printing the other books but the first one when the table is sorted.
I know that there's no such thing like break, so I thought using <xsl:if> block to check if the row is the first or not. Is this idea possible? Or can I do this in another way?
so I thought using
<xsl:if>block to check if the row is the first or not.
Yes, this is the correct idea:
<xsl:for-each select="/data/book">
<xsl:sort select="price" data-type="number" order="descending"/>
<xsl:if test="position()=1">
<xsl:value-of select="title"/>
</xsl:if>
</xsl:for-each>
Note that this selects only the first most expensive title in case of a tie.
Or can I do this in another way?
That depends on which XSLT processor you use. In XSLT 2.0, you can use the max() function. And several XSLT 1.0 processors support the math:max() and math:highest() extension functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With