XSLT Script Block Sample

 

This example illustrates how to use a script block in MSXML 6.0. In MSXML 6.0, the use of script blocks is disabled by default. You can enable the script block feature by setting the AllowXsltScript property to true. If AllowXsltScript is not set to true and you try to use a script block, an exception will be thrown.

The following JScript code tries to use a sample XSLT style sheet (script.xsl) to transform a sample XML file (customers.xml). When you run the code, you receive the following error message:

Security settings do not allow the execution of script code within this stylesheet.  

You receive this error message because AllowXsltScript has not been set to true on the DOM object where the style sheet is loaded.

JScript File (testxslscript.js)

var source = new ActiveXObject("Msxml2.DOMDocument.6.0");  
source.async = false;  
source.resolveExternals = true;     
source.load("customers.xml");  
if (source.parseError.errorCode != 0)   
{  
    WScript.Echo("nReason: " + source.parseError.reason);  
}   
else   
{  
   // Load style sheet.  
   var stylesheet = new ActiveXObject("Msxml2.DOMDocument.6.0");  
   stylesheet.async = false  
   stylesheet.resolveExternals = true;     
   //if the following line is commented out an exception will be thrown  
   //stylesheet.setProperty("AllowXsltScript", true);  
   stylesheet.load("script.xsl");  
   if (stylesheet.parseError.errorCode != 0)   
   {  
      WScript.Echo("nReason: " + stylesheet.parseError.reason);  
      WScript.Echo("nSource: " + stylesheet.parseError.srcText);   
      WScript.Echo("nLine: " + stylesheet.parseError.line);  
    }   
    else   
    {  
        try  
        {  
        source.transformNode(stylesheet);  
        WScript.Echo(source.xml);  
        }  
        catch (exception)   
        {  
        WScript.Echo(exception.description);  
        }  
   }  
}  
  

XML File (customers.xml)

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="script.xsl" ?>
<customers>
   <customer>
      <name>John Smith</name>
      <address>123 Elm St.</address>
      <phone>(123) 456-7890</phone>
   </customer>
   <customer>
      <name>Mary Jones</name>
      <address>456 Oak Ave.</address>
      <phone>(156) 789-0123</phone>
   </customer>
</customers>

XSLT File (script.xsl)

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:msxsl="urn:schemas-microsoft-com:xslt"
      xmlns:user="http://mycompany.com/mynamespace">

<msxsl:script language="JScript" implements-prefix="user">
   function xml(nodelist) {
      return nodelist.nextNode().xml;
   }
</msxsl:script>

<xsl:template match="/">
   <xsl:value-of select="user:xml(.)"/>
</xsl:template>

</xsl:stylesheet>

XSLT Security

Show: