0

I have the following XML and XSLT to transform to HTML.

XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <te>t1</te>
</root>

XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:output method="html" indent="yes" />
   <xsl:template match="root">
      <html>
         <div>
            <xsl:variable name="name1" select="te" />
            **
            <xsl:value-of select="CtrlList['$name1']" />
            **
         </div>
         <script language="javascript">var List={
        "t1":"test"
    }</script>
      </html>
   </xsl:template>
</xsl:stylesheet>

So my objective is get the value of "te" from the XML and map it with the JavaScript object "List" and return the value test while transforming with the XSLT. So i should get the value test as output.

Can anyone figure out what wrong in the XSLT.

Dairo
  • 822
  • 1
  • 9
  • 22
Tom Cruise
  • 1,395
  • 11
  • 30
  • 58

1 Answers1

0

When you look at your XSLT, it may seem like there is JavaScript there, but all XSLT sees is that it is outputing an element named "script", with an attribute "language", which contains some text. It is also worth noting that xsl:value-of is used to get the value from the input document, but your script element is actually part of the result tree, and so not accessible to xsl:value-of.

However, it is possible to extend XSLT so it can use javascript functions, but this is very much processor dependant, and you should think of it the same way as embedding JavaScript in HTML. Have a look at this question, as an example

How to include javaScript file in xslt

So, in your case, your XSLT would be something like this (Note this particular example will only work in Mircorsofts MSXML processor)

<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"
      exclude-result-prefixes="msxsl user">

  <xsl:output method="xml" indent="yes" />

 <msxsl:script language="JScript" implements-prefix="user">
   var List={
    "t1":"test"
   }

   function lookup(key) {
     return List[key];
   }
 </msxsl:script>

<xsl:template match="root">  
  <html>
    <div> 
      <xsl:variable name="name1" select="te"/>   
      <xsl:value-of select="user:lookup(string($name1))"/>
    </div>
  </html>
</xsl:template>
</xsl:stylesheet>

Of course, it might be worth asking why you want to use javascript in your XSLT. It may be possible to achieve the same result using purely XSLT, which would certainly make you XSLT more portable.

Community
  • 1
  • 1
Tim C
  • 70,053
  • 14
  • 74
  • 93