Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to Call JavaScript from XSL with Examples

Posted on 2003-03-10
18
Medium Priority
?
1,627 Views
Last Modified: 2013-11-19
I am trying to call Javascript from XSL.I am infant to XML/XSL Tech.so please help me out.I had set Classpath of js.jar,xalan.jar and bsf.jar .I am using XML spy version 5 Rel .3 .

Hello.xml ::::::::
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Hello.xsl"?>
<doc>
     <name first="David" last="Marston"/>
     <name first="David" last="Bertoni"/>
     <name first="Donald" last="Leslie"/>
     <name first="Emily" last="Farmer"/>
     <name first="Jack" last="Donohue"/>
     <name first="Myriam" last="Midy"/>
     <name first="Paul" last="Dick"/>
     <name first="Robert" last="Weir"/>
     <name first="Scott" last="Boag"/>
     <name first="Shane" last="Curcuru"/>
</doc>
::::::::::::::::::

Hello.xsl :::::::::::
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xalan"
                xmlns:counter="MyCounter"
                extension-element-prefixes="counter"
                version="1.0">

  <xalan:component prefix="counter"
                   elements="init incr" functions="read">
    <xalan:script lang="javascript">
      var counters = new Array();

      function init (xslproc, elem) {
        name = elem.getAttribute ("name");
        value = parseInt(elem.getAttribute ("value"));
        counters[name] = value;
        return null;
      }

      function read (name) {
        // Return a string.
        return "" + (counters[name]);
      }

      function incr (xslproc, elem)
      {
        name = elem.getAttribute ("name");
        counters[name]++;
        return null;
      }
    </xalan:script>
  </xalan:component>

  <xsl:template match="/">
    <HTML>
      <H1>Names in alphatebical order</H1>
      <counter:init name="index" value="1"/>
      <xsl:for-each select="doc/name">
        <xsl:sort select="@last"/>
        <xsl:sort select="@first"/>
        <p>
        <xsl:text>[</xsl:text>
        <xsl:value-of select="counter:read('index')"/>
        <xsl:text>]. </xsl:text>
        <xsl:value-of select="@last"/>
        <xsl:text>, </xsl:text>
        <xsl:value-of select="@first"/>
        </p>
        <counter:incr name="index"/>
      </xsl:for-each>
    </HTML>
  </xsl:template>
 
</xsl:stylesheet>



::::::::::::::::::::



Error ::::::::::

Names in alphatebical order
The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.


--------------------------------------------------------------------------------

Element 'counter:init' is not a recognized extension element.
 

:::::::::::::::::


so please help me out!!!!!!!!!!!!!!
Thanks Allot
0
Comment
Question by:sabooraj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +2
18 Comments
 
LVL 14

Expert Comment

by:avner
ID: 8101909
1. You cannot call javascript from within XSL. you can CALL javascript from the output of the XML/XSL .

2. The different parsers have different SPECIFIC extensions to allow calling a script at the time of the transformation, for example in MSXML :
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/htm/xsl_elm_qz_4s50.asp
0
 

Author Comment

by:sabooraj
ID: 8102264
I am using Java for XML/XSL Processing
0
 
LVL 14

Expert Comment

by:avner
ID: 8102384
Then you cannot use Javascript. MSXML is the only browsers allows Javascript extension at transformation time.
0
TCP/IP Network Protocol Cheat Sheet

TCP/IP is a set of network protocols which is best known for connecting the machines that make up the Internet. The truth is that TCP/IP is one of the oldest network protocols and its survival is mainly based on its simplicity and universality.

 
LVL 8

Expert Comment

by:Zlatin Zlatev
ID: 8102859
@avner, xalan also allows using scripts. Read the question carefully. Also as you have said it is specific, thus is not compatible with MS XML implementation, and may not be supported by XML Spy.

@sabooraj, are you sure you cannot achieve the desired result using pure xslt?
Why do you need the code in the XSLT stylesheet?
If you only need to add a counter to your XSL Transformation, then you can use named templates with parameters.

Kind Regards,
Zlatin Zlatev
0
 

Author Comment

by:sabooraj
ID: 8102977
@avner ,As Zlatev is saying very true that XALAN is providing to use Javascript in XSL and i am trying same.
Thanks allot for ur cooperation.

@Zlatev ,Really above code is not giving desired result.
Exact requirement is Different than what i am trying.I am just doing R & D first and then i will use that in my Reuiremnets.I just want to call Javascript thr XSL.
That's why i am trying above code.
I am referring this link

http://xml.apache.org/xalan-j/extensions.html#supported-lang

Actual requirement is to use .js Script file thr XSL.
Actually i am working on Server side and I have to send  Client(Vc++) some HTML Files by processing XML/XSL/JavaScript Files on server side on fly.If u have any examples in which used XML/XSL/Javascript to generate HTML output then please send me.
my mail id is <rajkumar@geodesiconline.com>
If have any other way to fulfill my requirements then please ur welcome
Thanks Allot!
0
 

Author Comment

by:sabooraj
ID: 8103234
Actually i was on wrong track to call Javascript from XSL.
Actually i want to add Javascript .js file into XSL and want to call Javascript Methos from XSL.
Now i am on track !!
Please help me out for doing same!
If anybody have examples for same then it's welcome.
Thanks Allot!
0
 
LVL 8

Accepted Solution

by:
Zlatin Zlatev earned 200 total points
ID: 8103292
0
 

Author Comment

by:sabooraj
ID: 8112464
@ Zlatev Thanks Allot for ur kind Help....
but stucked in between......
Please help me out ......

XSL File :::::::::

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:a="DAV:" xmlns:d='urn:schemas-microsoft-com:office:office' xmlns:user="http://www.compaq.com/userfunctoins" version="1.0">
<msxsl:script language="JavaScript" implements-prefix="user" >
var ii = 0;

function folderh(){
    ii += 1;
    return (ii);
}
</msxsl:script>
<xsl:template match="/news">
<html>
     <head>
     </head>
     <body bgcolor="#DCCFFC" >
      <xsl:value-of select="user:folderh()"/>
     </body>
     </html>
</xsl:template>
</xsl:stylesheet>


::::::::::::::::::
XML File ::::::;

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="WithXalannews.xsl"?>

<news>
</news>

::::::::::::::::::::



Above Code Works Fine but When Trying to add Javascript from .js file thr src attribute ....it's giving error .....src object  not Works with MSXML.....
so tried using other code by using Url's which u(Zlatev) had sent.
Please help me out .....
Giving All files





WithXalannews.XSL File ::::::::

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:math="http://exslt.org/math"
                xmlns:xalan="http://xml.apache.org/xslt"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                extension-element-prefixes="math msxsl xalan">

<xsl:script implements-prefix="user" language="javascript"
            src="math.js" />
<xsl:template match="/news">
<html>
     <head>
     </head>
     <body bgcolor="#DCCFFC" >
      <xsl:value-of select="user:folderh()"/>
     </body>
     </html>
</xsl:template>
</xsl:stylesheet>

:::::::::::::::

news.XML File :::::::::

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="WithXalannews.xsl"?>

<news>
</news>

::::::::::::::::::

Math.js File::::::::


var ii = 0;

function folderh(){
    ii += 1;
    return (ii);
}

::::::::::::::::


Above Code is not working Fine It's Giving Error ::::

The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.

--------------------------------------------------------------------------------

Keyword xsl:script may not be used in namespace http://www.w3.org/1999/XSL/Transform.
 
::::::::::::::::::::::::::::::::::::::::::
0
 

Expert Comment

by:sukesh
ID: 8117589
First of all, for scripts with msxsl, you need to use CDATA like below and then try.

<msxsl:script implements-prefix="scripts">
       <![CDATA[
       function showXML(nodelist)
           {
           
 }
       ]]>
</msxsl:script>


Check out my website completely done using XML, XSL/XSLT.
http://www.v4cnet.com

Rgds
Sukesh
0
 
LVL 8

Expert Comment

by:Zlatin Zlatev
ID: 8117635
@sabooraj,
You cannot use Xalan with IE. It is XML parser only for Java. I suppose that you try to view Xalan XSLT in Internet Explorer - this is why you recieve the error.

Note that you can combine Xalan and MSXML specific implementations in a single XSLT file, but you should ensure that you use only one of them and provide equivalent functions for both implementations.

HTH,
Zlatin Zlatev
0
 
LVL 2

Assisted Solution

by:stevenbaker
stevenbaker earned 200 total points
ID: 8120767
Hi,

There are a couple of issues here.

The first is that (as mentioned) you cannot use Xalan in IE.

Secondly, you cannot include post transformation script (in .js files) in an XSLT stylesheet.  - if you want to use .js just to increase reusability you can use an included stylesheet usin <xsl:import..> or <xsl:include..>

Thirdly, in the msxml implementation there are several factors to note:
-functions must ALWAYS return something as they have to be called in a xsl:value-of select="uesr:myFunction()"/>
this means for functions that increment a counter (for example) you need to return a blank string
- if passing in an xml node, it is always passed as a nodelist, even if it is only 1 node, so you will need to do the following:
<xsl:value-of select="user:doSomethingInJavascript(/root/my_node)"/>

where:

function doSomethingInJavascript(inNodeRef)
{
   var oNode=inNodeRef.nextNode();
   var attr=oNode.getAttribute("test");
   //do something!!
   return attr;
}

-when passing in attributes you need to explicitly convert them as in:
<xsl:value-of select="user:doSomethingInJavascript(string(/root/my_node/@my_attr))"/>
0
 

Author Comment

by:sabooraj
ID: 8142132
I am putting my Query in 2 messages.....
First i am giving you Working Code and then will Give Error Code.
When just added  msxml JavaScript and not used any methods then it's works fine.I had also used Javascript after Transformation.That works fine.

Continue..........





Working Code:::::::
news.xsl ::::::::::::

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:a="DAV:" xmlns:d='urn:schemas-microsoft-com:office:office' xmlns:user="http://www.compaq.com/userfunctoins" version="1.0">
                        <msxsl:script language="JavaScript" implements-prefix="user" >
                        <![CDATA[
                        var headlineCounter =1;
                        function returnHeadlineCounter(){
                            return (headlineCounter);
                        }

                        var innerLayerCounter =1;
                        function innerLayerCounterIncrementByOne(){
                            return innerLayerCounter + 1;
                        }
                        function returnInnerLayer(){
                               return innerLayerCounter;
                        }
                        
                        function innerLayerAssignmentByHeadline(){
                         innerLayerCounter= headlineCounter ;
                            return "";
                        }

                        function HeadlineIncrementAsPerTotalTabs(){
                        headlineCounter =innerLayerCounter + 2 ;
                            return "";
                        }
                        ]]>
                        </msxsl:script>

      
      <xsl:template match="/news">
            <html>
                  <head>
                        <style>
                                          font{COLOR:"#F53D74";font-family:arial}
                        </style>
                        <script language="JavaScript">
                        function accessCSS(layerID)
                        {
                              if(document.getElementById){
                                    return document.getElementById(layerID).style;
                              }else if(document.all){
                                    return document.all[layerID].style;
                              }else if(document.layers){
                                    return document.layers[layerID];
                              }
                        }
                        var DivVisible = null; /*Using for Storing Visible Layer Status*/
                        function toggleVis(layerID)
                        {
                              if (DivVisible != null)
                              {
                                    if(accessCSS(DivVisible).visibility=="visible")
                                    {
                                          accessCSS(DivVisible).visibility="hidden";
                                    }
                              }
                              accessCSS(layerID).visibility="visible";
                              DivVisible = layerID;
                        }
                        </script>
                  </head>
                  <body bgcolor="#DCCFFC">
                        <table border="1" cellspacing="0" width="100%" bordercolor="#F9bF00">
                              <tr>
                                    <td width="100%">
                                          <table border="0" cellspacing="5" width="100%" cellpadding="2" align="left">
                                                <xsl:apply-templates/>
                                          </table>
                                    </td>
                              </tr>
                        </table>
                  </body>
            </html>
      </xsl:template>
      <xsl:template match="category">
            <tr>
                  <td>
                        <span style="color:yellow">
                              <xsl:value-of select="@cname"/>
                        </span>
                  </td>
            </tr>
            <tr>
                  <xsl:apply-templates select="headline"/>
            </tr>
      </xsl:template>
      <xsl:template match="headline">
            <xsl:for-each select="news/category">
                  <tr align="center" style="font-weight:bold">
                        <xsl:apply-templates/>
                  </tr>
            </xsl:for-each>
      </xsl:template>
      <xsl:template match="headline">
            <tr>
                  <td>
                        <a href="javascript:toggleVis(1)">
                              <font>
                                    <xsl:value-of select="name"/>
                              </font>
                        </a><br><xsl:value-of select="kicker"/></br>
                        <div id="1" style="left:20;top:200px;position:absolute;border:'0.2cm groove pink';visibility:hidden">
                              <TABLE width="300">
                                    <tr>
                                          <td style="background-color:pink">Story</td>
                                          <td style="background-color:pink">
                                                <a href="javascript:toggleVis(2)">Related Story
                                          </a></td>
                                    </tr>
                                    <tr >
                                          <td colspan="2" style="background-color:pink">
                                                <xsl:value-of select="summary"/>
                                          </td>
                                    </tr>
                              </TABLE>
                        </div>
                        <xsl:apply-templates select="story"/>
                  </td>
            </tr>
      </xsl:template>

      <xsl:template match="story">
            <div id="2" style="left:20;top:200px;position:absolute;border:'0.2cm groove pink';visibility:hidden">
                  <TABLE width="300">
                        <tr>
                              <td style="background-color:pink">
                                    <a href="javascript:toggleVis(1)">Story
                                          </a></td>
                              <td style="background-color:pink">Related Story</td>
                        </tr>
                        <tr>
                              <td colspan="2" style="background-color:pink">
                                    <xsl:for-each select="headline">
                                          <xsl:element name="a">
                                          <xsl:attribute name="href"><xsl:value-of select="sturl"/></xsl:attribute>
                                          <xsl:attribute name="target">_blank</xsl:attribute>
                                          <font style="color:blue">
                                                      <br>
                                                            <xsl:value-of select="stname"/>
                                                      </br>
                                          </font>
                                          </xsl:element>
                                    </xsl:for-each>
                              </td>
                        </tr>
                  </TABLE>
            </div>
      </xsl:template>
</xsl:stylesheet>


::::::::::::::

news.xml ::::::::::::

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="news.xsl"?>
<news>
      <category cname="Sports">
            <headline>
                  <name>India VS Holand</name>
                  <url>http://cricket.khel.com</url>
                  <kicker>Some brief abt Match </kicker>
                  <summary>In a startup to their world cup campain india take on holand today.
                                          All eyes will be on Sachin's performance.
                  </summary>
                  <story>
                        <headline>
                              <stname>Know all about worldcup-2003</stname>
                              <sturl>http://www.webdunia.com/cricket/wc2003/index.htm</sturl>
                        </headline>
                        <headline>
                              <stname>Know all about worldcup-2004</stname>
                              <sturl>http://www.webdunia.com/cricket/wc2003/index.htm</sturl>
                        </headline>
                  </story>
            </headline>
      </category>
</news>


::::::::::::::::::::::




Continueeeeeeeeeeee
0
 

Author Comment

by:sabooraj
ID: 8142141
Thanks allot for everybody who is helping me.....thanks allot........
Continued from Last message

In Error Code when i am calling msxml Script methods using prefix user:returnInnerLayer() then Gives Error ::::
so please help me out.....

Then getting Error:::

Exception in thread "main" javax.xml.transform.TransformerException: javax.xml.t
ransform.TransformerException: Instance method call to method returnInnerLayer r
equires an Object instance as first argument
        at org.apache.xalan.extensions.ExtensionHandlerJavaPackage.callFunction(
ExtensionHandlerJavaPackage.java:395)


news.xsl :::::With Error Code

::::::::

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:a="DAV:" xmlns:d='urn:schemas-microsoft-com:office:office' xmlns:user="http://www.compaq.com/userfunctoins" version="1.0">
                        <msxsl:script language="JavaScript" implements-prefix="user" >
                        <![CDATA[
                        var headlineCounter =1;
                        var innerLayerCounter =1;
                                          
                        function returnHeadlineCounter(){
                            return (headlineCounter);
                        }


                        function innerLayerCounterIncrementByOne(){
                            return innerLayerCounter + 1;
                        }
                        function returnInnerLayer(){
                               return ( innerLayerCounter);
                        }
                        
                        function innerLayerAssignmentByHeadline(){
                         innerLayerCounter= headlineCounter ;
                            return "";
                        }

                        function HeadlineIncrementAsPerTotalTabs(){
                        headlineCounter =innerLayerCounter + 2 ;
                            return "";
                        }
                        ]]>
                        </msxsl:script>

      
      <xsl:template match="/news">
            <html>
                  <head>
                        <style>
                                          font{COLOR:"#F53D74";font-family:arial}
                        </style>
                        <script language="JavaScript">
                        function accessCSS(layerID)
                        {
                              if(document.getElementById){
                                    return document.getElementById(layerID).style;
                              }else if(document.all){
                                    return document.all[layerID].style;
                              }else if(document.layers){
                                    return document.layers[layerID];
                              }
                        }
                        var DivVisible = null; /*Using for Storing Visible Layer Status*/
                        function toggleVis(layerID)
                        {
                              if (DivVisible != null)
                              {
                                    if(accessCSS(DivVisible).visibility=="visible")
                                    {
                                          accessCSS(DivVisible).visibility="hidden";
                                    }
                              }
                              accessCSS(layerID).visibility="visible";
                              DivVisible = layerID;
                        }
                        </script>
                  </head>
                  <body bgcolor="#DCCFFC">
                        <table border="1" cellspacing="0" width="100%" bordercolor="#F9bF00">
                              <tr>
                                    <td width="100%">
                                          <table border="0" cellspacing="5" width="100%" cellpadding="2" align="left">
                                                <xsl:apply-templates/>
                                          </table>
                                    </td>
                              </tr>
                        </table>
                  </body>
            </html>
      </xsl:template>
      <xsl:template match="category">
            <tr>
                  <td>
                        <span style="color:yellow">
                              <xsl:value-of select="@cname"/>
                        </span>
                  </td>
            </tr>
            <tr>
                  <xsl:apply-templates select="headline"/>
            </tr>
      </xsl:template>
      <xsl:template match="headline">
            <xsl:for-each select="news/category">
                  <tr align="center" style="font-weight:bold">
                        <xsl:apply-templates/>
                  </tr>
            </xsl:for-each>
      </xsl:template>
      <xsl:template match="headline">
            <tr>
                  <td>
                        <a href="javascript:toggleVis(1)">
                              <font>
                                    <xsl:value-of select="name"/>
                              </font>
                        </a><br><xsl:value-of select="kicker"/></br>
                  <xsl:element name="div">
                              <xsl:attribute name="id"><xsl:value-of select = "user:returnInnerLayer()"/></xsl:attribute>
                              <xsl:attribute name="style"><xsl:value-of select =  "concat('','width:300;height:100;overflow-y: auto ;scrollbar-3dlight-color :red;left:20;top:200px;position:absolute;visibility:hidden')"/></xsl:attribute>
                              <TABLE width="300" >
                                    <tr>
                                          <td style="background-color:pink">Story</td>
                                          <td style="background-color:pink">
                                          <xsl:element name="a">
                                                <xsl:attribute name="href"><xsl:value-of select = "concat('javascript:toggleVis(',user:innerLayerCounterIncrementByOne(),')')"/></xsl:attribute>
                                                <font>Related Story</font>
                                          </xsl:element>
                                          </td>
                                    </tr>
                                    <tr >
                                          <td colspan="2" style="background-color:pink">
                                                <xsl:value-of select="summary"/>
                                          </td>
                                    </tr>
                              </TABLE>
                        </xsl:element>

                        <xsl:apply-templates select="story"/>
                  </td>
            </tr>
      </xsl:template>

      <xsl:template match="story">
            <div id="2" style="left:20;top:200px;position:absolute;border:'0.2cm groove pink';visibility:hidden">
                  <TABLE width="300">
                        <tr>
                              <td style="background-color:pink">
                                    <a href="javascript:toggleVis(1)">Story
                                          </a></td>
                              <td style="background-color:pink">Related Story</td>
                        </tr>
                        <tr>
                              <td colspan="2" style="background-color:pink">
                                    <xsl:for-each select="headline">
                                          <xsl:element name="a">
                                          <xsl:attribute name="href"><xsl:value-of select="sturl"/></xsl:attribute>
                                          <xsl:attribute name="target">_blank</xsl:attribute>
                                          <font style="color:blue">
                                                      <br>
                                                            <xsl:value-of select="stname"/>
                                                      </br>
                                          </font>
                                          </xsl:element>
                                    </xsl:for-each>
                              </td>
                        </tr>
                  </TABLE>
            </div>
      </xsl:template>
</xsl:stylesheet>


:::::::::


0
 
LVL 8

Expert Comment

by:Zlatin Zlatev
ID: 8306088
<q>Actually i am working on Server side and I have to send  Client(Vc++) some HTML Files by processing XML/XSL/JavaScript Files on server side on fly.If u have any examples in which used XML/XSL/Javascript to generate HTML output then please send me.
</q>

@sabooraj, do you mean that you have specific client? not an ordinary browser?
What server do you have? Apache with Java&Xalan?
Will be there any XSL Transformation on the client? If yes - what parser will you use? MSXML?
0
 
LVL 8

Expert Comment

by:Zlatin Zlatev
ID: 12538561
Thank you
0
 
LVL 2

Expert Comment

by:stevenbaker
ID: 12538576
thanks
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question