Good coding style to do case-select in XSLT
Posted
by
Scud
on Stack Overflow
See other posts from Stack Overflow
or by Scud
Published on 2011-02-05T04:28:26Z
Indexed on
2011/02/05
23:25 UTC
Read the original article
Hit count: 283
I want to have a page display A,B,C,D depending on the return value from XML value (1,2,3,4). My approaches are by javascript or XSLT:choose. I want to know which way is better, and why? Can I do this case-select in .cs code (good or bad)? Should I javascript code in XSLT? Can the community please advise? Thanks.
Below are the code.
Javascript way (this one works):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:js="urn:custom-javascript">
<xsl:template match="page">
<msxsl:script language="JavaScript" implements-prefix="js">
<![CDATA[
function translateSkillLevel(level)
{
switch (level)
{
case 0: return "Level 1";
case 1: return "Level 2";
case 2: return "Level 3";
}
return "unknown";
}
]]>
</msxsl:script>
<div id="skill">
<table border="0" cellpadding="1" cellspacing="1">
<tr>
<th>Level</th>
</tr>
<xsl:for-each select="/page/Skill">
<tr>
<td>
<!-- difference here -->
<script type="text/javascript">
document.write(translateSkillLevel(<xsl:value-of select="@level"/>));
</script>
</td>
</tr>
</xsl:for-each>
</table>
</div>
</xsl:template>
</xsl:stylesheet>
Javascript way (this one doesn't work, getting undefined js tag):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:js="urn:custom-javascript">
<xsl:template match="page">
<msxsl:script language="JavaScript" implements-prefix="js">
<![CDATA[
function translateSkillLevel(level)
{
switch (level)
{
case 0: return "Level 1";
case 1: return "Level 2";
case 2: return "Level 3";
}
return "unknown";
}
]]>
</msxsl:script>
<div id="skill">
<table border="0" cellpadding="1" cellspacing="1">
<tr>
<th>Level</th>
</tr>
<xsl:for-each select="/page/Skill">
<tr>
<td>
<!-- difference here -->
<xsl:value-of select="js:translateSkillLevel(string(@level))"/>
</td>
</tr>
</xsl:for-each>
</table>
</div>
</xsl:template>
</xsl:stylesheet>
XSLT way:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
<div id="skill">
<table border="0" cellpadding="1" cellspacing="1">
<tr>
<th>Level</th>
</tr>
<xsl:for-each select="/page/Skill">
<tr>
<td>
<xsl:choose>
<xsl:when test="@level = 0">
Level 1
</xsl:when>
<xsl:when test="@level = 1">
Level 2
</xsl:when>
<xsl:when test="@level = 2">
Level 3
</xsl:when>
<xsl:otherwise>
unknown
</xsl:otherwisexsl:otherwise>
</xsl:choose>
</td>
</tr>
</xsl:for-each>
</table>
</div>
</xsl:template>
</xsl:stylesheet>
EDIT:
Also, I have some inline javascript functions for form submit.
<input type="submit" onclick="javascript:document.forms[0].submit();return false;"/>
© Stack Overflow or respective owner