My code below seems logical however i don’t know why the sorting doesn’t work with the error “Variable or parameter ‘sort’ is undefined.’“? Im suspecting there are something wrong with declaring param in xsl. Could anyone point my mistake? thanks
java code to pass parameter
String sort = "rating";
transformer.setParameter("sort", sort); /It will control the sort in xsl
xml file
<?xml version="1.0" ?>
<cd>
<title>A Funk Odyssey</title>
<artist>Jamiroquai</artist>
<tracklist>
<track id="1">
<title>Feels So Good</title>
<time>4:38</time>
<rating>2</rating>
</track>
<track id="2">
<title>Little L</title>
<time>4:10</time>
<rating>5</rating>
</track>
<track id="3">
<title>You Give Me Something</title>
<time>5:02</time>
<rating>3</rating>
</track>
<track id="4">
<title>Corner of the Earth</title>
<time>3:57</time>
<rating>1</rating>
</track>
</tracklist>
</cd>
This is my xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes"/>
<xsl:param name="sort" select="title"/>
<xsl:template match="/">
<table border="1">
<thead>
<tr>
<th><a href="#">Title</a></th>
<th><a href="#">Time</a></th>
<th><a href="#">Rating</a></th>
</tr>
</thead>
<tbody>
<xsl:for-each select="cd/tracklist/track">
<xsl:sort select="$sort"/>
<tr>
<td><xsl:value-of select="title" /></td>
<td><xsl:value-of select="time" /></td>
<td><xsl:value-of select="rating" /></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</xsl:template>
</xsl:stylesheet>
In your
xsl:paramdeclaration you are trying to default to$sortwhich is not defined at the timexsl:paramis evaluated. It does look like a reference to itself.If you don’t need a default then just change your parameter declaration to:
or default to a string value:
or
That said, we have only addressed the parameter declaration issue. Now on to sorting. The
xsl:sortneeds an expression, it won’t convert a string value into XPath like you expect it to.Here’s a solution: Using Variables in
<xsl:sort select=""/>.You would basically do something like: