|
Summary
How to select DISTINCT items from XML via XSLT
Like SQL query "SELECT DISTINCT year FROM projets" ?
To use "preceding-sibling", like select="/publish/book[not(year = preceding-sibling::book/year)]
How to select DISTINCT items from XML via XSLT Like SQL query SELECT DISTINCT year FROM projets ?
Say, we have the following XML:
<publish> <book> <year>1998</year> <title>This is the first book</title> </book> <book> <year>2000</year> <title>This is the second book</title> </book> <book> <year>1999</year> <title>This is the third book</title> </book> <book> <year>2000</year> <title>This is the fourth book</title> </book> <book> <year>1998</year> <title>This is the fifth book</title> </book> <book> <year>1977</year> <title>This is the sixth book</title> </book> </publish>
How can we retrieve a list of one book in each year such as: 1977 This is the sixth book 1998 This is the first book 1999 This is the third book 2000 This is the second book ?
If the same data in the relational database table, we can easily get this information by SELECT DISTINCT year FROM projets SQL query.
The answer is using preceding-sibling: select=/publish/book[not(year = preceding-sibling::book/year)]
Please see the XML and XSL file for details, the resluts is: 1977 This is the sixth book 1998 This is the first book 1999 This is the third book 2000 This is the second book
Be careful the the namespace for XSL here must be xmlns:xsl=http://www.w3.org/1999/XSL/Transform. The xmlns:xsl=http://www.w3.org/TR/WD-xsl doesn't work-you will get transformation error, it doesn't know what preceding-sibling:: means.
I am sure W3 or Microsoft will come up with a function called DISTINCT like: select=DISTINCT(/publish/book/year), but untill then, preceding-sibling is not the bad solution.
<?xml-stylesheet type=text/xsl href=E:\InvSearch\test2.xsl?> <publish> <book> <year>1998</year> <title>This is the first book</title> </book> <book> <year>2000</year> <title>This is the second book</title> </book> <book> <year>1999</year> <title>This is the third book</title> </book> <book> <year>2000</year> <title>This is the fourth book</title> </book> <book> <year>1998</year> <title>This is the fifth book</title> </book> <book> <year>1977</year> <title>This is the sixth book</title> </book> </publish>
<?xml version=1.0 encoding=UTF-8?> <xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform> <xsl:template match=/> <table> <xsl:for-each select=/publish/book[not(year = preceding-sibling::book/year)]> <xsl:sort select=year data-type=number order=ascending/> <tr> <td> <xsl:value-of select=year/> </td> <td> <xsl:value-of select=title/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
| Further additional information | |
Updating comments...
Updating comments...
|