Search code examples
xsltmsxsl

calling function with xslt using xpath selection


How can I call javascript/c# function in xslt passing xpath selection value. Here is how I call function with manualy typed parameter:

<xsl:value-of select="cs:my('some text')"/>

Solution

  • Here is an example from the MSXML 4 SDK (this should be the same for MSXML 6, and is quite similar for .NEt's XslCompiledTransform -- for the latter search MSDN for <msxsl:script>)

    Example This example defines a script block with a namespace prefix of user that contains a function called xml that takes a node-list as an argument. Later, this function, xml(nodelist) in the user namespace, is called from the select attribute of .

    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>
    

    Formatted Output

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