How can I convert a string to upper- or lower-case with XSLT?
.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="utils" language="C#">
<![CDATA[
public string ToLower(string stringValue)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(stringValue))
{
result = stringValue.ToLower();
}
return result;
}
]]>
</msxsl:script>
<!-- using of our custom function -->
<lowercaseValue>
<xsl:value-of select="utils:ToLower($myParam)"/>
</lowercaseValue>
Assume, that can be slow, but still acceptable.
Do not forget to enable embedded scripts support for transform:
// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);
XslCompiledTransform xslt = new XslCompiledTransform();
// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());
XSLT 2.0 has upper-case()
and lower-case()
functions. In case of XSLT 1.0, you can use translate()
:
<xsl:value-of select="translate("xslt", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")" />
In XSLT 1.0 the upper-case()
and lower-case()
functions are not available.
If you're using a 1.0 stylesheet the common method of case conversion is translate()
:
<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:template match="/">
<xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>