SoFunction
Updated on 2025-04-08

XSL brief tutorial (5) XSL index

Original: Jan Egil Refsnes Translation: Ajie

V. XSL index


If I need to arrange the display of elements in a certain order, how should I establish an index of XSL?

Let's look at the previous example, and this code:


<?xml version="1.0" encoding="ISO8859-1" ?>

<CATALOG>

<CD>

<TITLE>Empire Burlesque</TITLE>

<ARTIST>Bob Dylan</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Columbia</COMPANY>

<PRICE>10.90</PRICE>

<YEAR>1985</YEAR>

</CD>

.

.

.


When an XML document is converted into an HTML file, the index should be created at the same time. The simple way is to add an order-by attribute to your for-each element, just like this:

<xsl:for-each select="CATALOG/CD" order-by="+ ARTIST">

The order-by attribute has a symbol of "+" or "-" to define the index, whether it is arranged in ascending or descending order. The name after the symbol is the keyword to be indexed.

For example (cd_catalog_sort.xsl):

<?xml version='1.0'?>

<xsl:stylesheet xmlns:xsl="http:///TR/WD-xsl">

<xsl:template match="/">

<html>

<body>

<table border="2" bgcolor="yellow">

<tr>

<th>Title</th>

<th>Artist</th>

</tr>

<xsl:for-each select="CATALOG/CD" order-by="+ ARTIST">

<tr>

<td><xsl:value-of select="TITLE"/></td>

<td><xsl:value-of select="ARTIST"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>


Finally, we use the following HTML code to display the index results, you can try it yourself.

<html>

<body>

<script language="javascript">

// Load XML

var xml = new ActiveXObject("")

= false

("cd_catalog.xml")


// Load the XSL

var xsl = new ActiveXObject("")

= false

("cd_catalog_sort.xsl")


// Transform

((xsl))

</script>


</body>

</html>