Thursday, June 18, 2009

xslt function upper-case() in MSXML transformations

Today I wanted to use xslt to convert some incoming element to upper case so I can then use it in a look up routine. (mentioned in previous blog) Some simple Googling will most likely point to the XPath Version="2.0" function fn:upper-case(string).

However, using Microsoft's MSXML this function is not supported by their transformation engine. However, the fn:translate(...) function is supported so here is a simple way to convert all letters to uppercase.


Here is a sample conversion template:



<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="iso-8859-1" indent="yes" />
<xsl:variable name="lcletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
<xsl:variable name="ucletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
<xsl:template match="convert">
<converted>
<toupper><xsl:value-of select="translate(lower,$lcletters,$ucletters)" /></toupper>
<tolower><xsl:value-of select="translate(upper,$ucletters,$lcletters)" /></tolower>
<touppermixed><xsl:value-of select="translate(mixed,$lcletters,$ucletters)" /></touppermixed>
</converted>
</xsl:template>
</xsl:stylesheet>



Here is a sample xml file:

<?xml version='1.0'?>
<convert>
<lower>convert to upper</lower>
<upper>CONVERT TO LOWER</upper>
<mixed>Convert This To All Upper</mixed>
</convert>


Here is a sample asp vbscript page:

<%@ Language=VBScript %>

<%Option Explicit%>

<%
Dim xslt
Dim xslProc
Dim xslDoc
Dim oXmlDoc
Set oXmlDoc = Server.CreateObject("Microsoft.XMLDOM")
oXmlDoc.load(Server.MapPath("convert.xml"))

set xslDoc = Server.CreateObject("MICROSOFT.FreeThreadedXMLDOM")
xslDoc.async = false
xslDoc.load(Server.MapPath("conversion.xsl"))

if xslDoc.parseError.errorCode = 0 Then
set xslt = Server.CreateObject("Msxml2.XSLTemplate")
xslt.stylesheet = xslDoc
set xslProc = xslt.createProcessor()
xslProc.input = oXmlDoc
xslProc.transform()
response.write "Conversion =" & Server.htmlencode(xslProc.output)
else
response.write "Error::" & xslDoc.parseError.reason
end if

%>



Give it a shot you should end up with something like:

Conversion =<?xml version="1.0" encoding="UTF-16"?> <converted> <toupper>CONVERT TO UPPER</toupper> <tolower>convert to lower</tolower> <touppermixed>CONVERT THIS TO ALL UPPER</touppermixed> </converted>

No comments:

Post a Comment