Archive for the ‘ XSL ’ Category

Calling Multiple Windows Onload Functions In Javascript

Saturday, March 7th, 2009 By Nikhil

Heres another little peice of Javascript trickery that I had to dig around because the situation commaned it. In one of my web sites, I had this situation where I had to implement “windows.onload” twice. The first thing that would came to an inexperienced mind like mine ( I have to honestly say that, since I have been using javascript Frameworks and libraries, I have forgotton to do simple things on my own… sad but true), is the following method…

window.onload=onloadfn1;
window.onload=onloadfn2;
window.onload=onloadfn3;
etc...

Sorry to say but, this wont work… dont want to discuss the execution science of Javascript much … but according to my recent experience, only the last function (onloadfn3) will ill actually get executed.

In normal situations, unlike mine (which I’ll talk about a little later)… you could do one of the following to execute mutliple onload functions ….

OR something like this

function doOnLoad() {
        onloadfn1();
        onloadfn2();
        onloadfn3();
}
window.onload = doOnLoad;

For my current situation , I cannot use either of the above…
Why did I need to call windows.onload twice, rather that calling two functions within a single onload function? Here is quick look at my problem statement…

“My Site pages are structured like the WORDPRESS theme…. i.e. there is a common Header.php and Footer.php that gets included into all the site pages. There is an onload function implementaion in the Footer.php to do some common onload functions. AND there are few pages that need to something of their own ONLOAD , apart from those done by the common onload function. If I assign callback function directly to the window.onload handler, it will over-ride previously assigned callbacks in the Footer.php”

…. Is my problem understood :) ?

Well! there are few solutions that I did find. They all are very similar and mainly implementions of a solution given by Simon Willison (http://simonwillison.net/2004/May/26/addLoadEvent/)…

Solution :

Simply add this javascript code to site …

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
       window.onload = func
    } else {
       window.onload = function() {
           if (oldonload) {
                  oldonload()
          }
          func()
       }
   }
} 

And call it instead of the usual “windows.onload”

addLoadEvent(FunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load *
}); 

Advantages of this code snippet …
1. Primarily, It lets you have multiple windows.onload events, called from seperate parts of your code, without overridding the previous definition
2. It is really unobtrusive. It can be placed in a file with your other scripts or in a separate file.
3. It works even if window.onload has already been set.


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


TEXTAREA Collapse problem in XSL/XSLT

Saturday, September 20th, 2008 By Nikhil


PROBLEM STATEMENT:

I ran into this a problem regarding textareas in XSLs.  In simple words, the problem arises when you have a blank <textarea> tag, then it will collapse it to <textarea />.
i.e. if you had something like the following in your XSL and the XML data for the TEXTAREA value, returns nothing…

<textarea name=’description’ ><xsl:value-of select=”DESCRIPTION”/></textarea>

As browsers don’t recognise this, it will cause the rest of the form HTML to run into the text area.

POSSIBLE SOLUTIONS:

In the XSL, add a non-breaking-space ( ) after the xsl:value tag.BEWARE, to take care of this extra space you added, during client side validations of this field.

<textarea  name=’description’ ><xsl:value-of select=”DESCRIPTION”/> </textarea>

Or
<xsl:value-of select=”concat (DESCRIPTION,’ ‘)”/>

Or
Insert a <xsl:value-of select=”@unknown” /> tag pointing to an unknown attribute. This will force the PHP XSLT parser to generate an opening and closing text area tag, even if it has nothing in between.

Or
Insert a <xsl:text> field containing a space to force a closing tag.

However, though the above mentioned solutions might seem to fix the problem, I am still not convinced that they are right and best ways to fix it. If there is any other better way of fixing this quirk, Please do let us know.


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


A Variety of XSL Test Conditions (Collection of XSL:IF and XSL:WHEN TEST Conditions)

Sunday, September 14th, 2008 By Nikhil

Every time I have to do a XSL:IF or XSL:WHEN test, I have go back to the reference books. I never seem to remember them. Thought there would be more out there, just like me, who would rather prefer to have all of them, possible, at one place, ready to be referred when needed.

For those who are new … Syntax for XSL:IF

<xsl:if test=”expression”>
<!– Content: template –>
</xsl:if>

The xsl:if/xsl:when Test Collection
The conditions below are all simple and self explanatory. So I believe it won’t need much explanation

<xsl:if test=”position()=last()-1″>
This if the last but one element in the list!
</xsl:if>

<xsl:if test=”SALARY > 5000″>
The salary of this person is greater than Rs. 5000
</xsl:if>

<xsl:if test=”count(JOBS) > 3″>
There are more than 3 jobs in this list!
</xsl:if>

<xsl:if test=”(@DEPT = ‘SALES’) or (@JOINYEAR = ’1997′)”>
       This person is from sales department OR his Year of Joining is 1997
</xsl:if>

<xsl:if test=”EXPERIENCE”>
       This person have atleast one EXPERIENCE child element.
</xsl:if>

<xsl:if test=”@HOBBY”>
    The person has a hobby attribute.
</xsl:if>

The same text conditions could be used for XSL:CHOOSE/XSL:WHEN as well

xsl:choose

XSLT’s  xsl:choose instruction is similar to xsl:if but has a few key differences:
• One xsl:choose element can test for more than one condition and add different nodes to the result tree based on which condition is true. 
• An xsl:choose element can have a default template to add to the result tree if none of the conditions are true. (Compare xsl:if, which has no equivalent of an “else” condition.)
• The xsl:choose element has specific subelements that are necessary for it to work, while you can put any well-formed elements you want inside of an xsl:if element.

<xsl:choose>
<xsl:when test=”boolean-expression”>
   Do something when this boolean-expression is TURE
</xsl:when>
<xsl:otherwise> Do something else </xsl:otherwise>
</xsl:choose>


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


Tokenizing Delimited String inside an XSL

Wednesday, August 13th, 2008 By Nikhil

If your requirement is to split a node value in an XML, that contains a delimited string of value, into individual items, then you have reached the right place … have a look at the example below. If you are familiar with a little bit of XML and XSL … I don’t think you would need any explanation.
Also, this example includes usage of XSL functions like xsl:call-template , xsl:substring-before, xsl:substring-after, if that’s what you are after.

XML to be transformed (food.xml):-
Assume the task is to tokenize the string delimited by comma, in the the tag “keywords”

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="food.xsl"?>
<food>
<date>July 2008</date>
<description>All about things we eat everyday</description>
<keywords>Fruits, Vegetables, Pulses, Meat, Cereals </keywords>
</food>

XSL (food.xsl):-

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>XSL 1.0 Delimited String Tokeniser</title>
</head>
<body>
<xsl:value-of select="food/meta"/>
<div >
<xsl:call-template name="tokenize">
<xsl:with-param name="string" select="food/keywords" />
<xsl:with-param name="delimitr" select="','" />
</xsl:call-template>

</div>
</body>
</html>
</xsl:template>
<xsl:template name="tokenize">
<xsl:param name="string" />
<xsl:param name="delimitr" />
<xsl:choose>
<xsl:when test="contains($string, $delimitr)">
<div style="border:1px solid red;">
<h3><xsl:value-of select="substring-before($string,$delimitr)" /></h3>
<xsl:variable name="data" select="substring-before($string,$delimitr)"/>
</div>
<xsl:call-template name="tokenize">
<xsl:with-param name="string" select="substring-after($string, $delimitr)" /><xsl:with-param name="delimitr" select="$delimitr" /></xsl:call-template>
</xsl:when>
<xsl:otherwise>
<div style="border:1px solid red;">
<h3><xsl:value-of select="$string" /></h3>
</div>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

Resultant output HTML :-

<div>
<div style="border: 1px solid red;">
<h3>Fruits</h3>
</div>
<div style="border: 1px solid red;">
<h3> Vegetables</h3>
</div>
<div style="border: 1px solid red;">
<h3> Pulses</h3>
</div>
<div style="border: 1px solid red;">
<h3> Meat</h3>
</div>
<div style="border: 1px solid red;">
<h3> Cereals </h3>
</div>
</div>

Needless to say … just change the parameter “delimitr” to the delimiter of your choice


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


A problem with position() in XSL … or is it?

Monday, August 4th, 2008 By Nikhil

I had this strage problem while creating a XSL today. Looked for answers throughout the net, but couldnt find any …. Actually I guess! I dint know what my problem was, so what do I look for?

Anyway! Just in case you have this very same problem too and somehow by the power of the FORCE you managed to land on this page … you would thank me tons … And if you have accidently landed on this page for some strange fate and you happen to be a XSL developer , DO MAKE A NOTE OF THIS NOW, FOR THE FUTURE cause, If some day, you face this issue, then the FORCE might not be with you.

Problem statement:
I have this XML , where there are two nodes with multiple items in it and the items between these two nodes have a one to one correspondence. In the example below, each item in the node <array name=”PLAYURL” /> relates( corresponding position) to an item in the node <array name=”SITENAME” />

<?xml version="1.0" encoding="utf-8"?>
<myplaylists>
<playlist>
<title>Best of Rest </title>
<array name="SITENAME">
<str>www.musicindiaonline.com</str>
<str>www.dhingana.com</str>
<str>www.raaga.com</str>
<str>www.smashits.com</str>
<str>www.desimusic.com</str>
<str>www.musicplug.in</str>
</array>
<array name="PLAYURL">
<str>http://www.musicindiaonline.com/123/</str>
<str>http://www.dhingana.com/play/123</str>
<str>http://www.raaga.com/123</str>
<str>http://ww.smashits.com/123</str>
<str>http://www.desimusic.com/123</str>
<str>http://www.musicplug.in/123</str>
</array>
</playlist>
</myplaylists>

Now, I have a loop , where i loop through <array name=”SITENAME”>, and I want to get the related item( at the corresponding position) in <array name=”PLAYURL”>,

What you would normaly try do is …

<xsl:for-each select="myplaylists/playlist/array[@name='SITENAME']/str">
play from : <a href="{../../array[@name='PLAY']/str[position()]}"/> <xsl:value-of select="." /></a>
</xsl:for-each>

SORRY!! THIS WONT WORK … Ah!!!! Surpised …

Now you would probably want to try , something like this …

<xsl:for-each select="myplaylists/playlist/array[@name='SITENAME']/str">
<xsl:variable name="pos"> <xsl:value-of select="position()"/></xsl:variable>
play from : <a href="{../../array[@name='PLAY']/str[$pos]}"/> <xsl:value-of select="." /></a>
</xsl:for-each>

And Again this wont work … Now you scratching your head, trying to contact everyone who you think knows some XSL and could be of any help … you try every other option … and still it wont work … Well! Thats what happened to me atleast …

DONT DESPAIR !!! TRY THIS

<xsl:for-each select="myplaylists/playlist/array[@name='SITENAME']/str">
<xsl:variable name="pos-int" select="position()" />
play from : <a href="{../../array[@name='PLAY']/str[$
pos-int]}"/> <xsl:value-of select="." /></a>
</xsl:for-each>

DONT ASK ME WHY IT WORKS. Cause i dont have a right reason… if you do! Please do drop a comment. It might be pretty usefull. Also! if you have better TITLE for this post, do drop me a line :)


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


Setting the DOCTYPE in XSL

Saturday, August 2nd, 2008 By Nikhil

Last week I created a progessive HTML/CSS layout for a client, tested it in IE6, IE7 and FF 3, seemed perfectly fine… UNTIL! the layout went further down the manufacting cycle. It failed. Page layout elements just went all over the place when the HTML layout was converted into  XSL and  XML applied to it … Bummer!!!

Could not sleep ok over the weekend, in anticipation of Monday morning, when I’ll have to fix this SH**. But now having a little experince in dealing with these kind of situations ( Browser Quirks, I mean), I knew it had to do with nothing else but DOCTYPE…. and It WAS…

The Problem:
You want control over the DOCTYPE, since your transformation will include a default DOCTYPE explicitly, and you layout will be out for a toss.

The Solution:
XSLT specs provides output methods to set a the DOCTYPE of choise. Also, for us UI developers, the topics of interest would be HTML output methods and XML output methods.

Well! before you get bored , here is the fix.

For eg., if you had the following DOCTYPE in your HTML version :-

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Then in the XSL you would have to have the following :-

<xsl:output method="html" doctype-system="http://www.w3.org/TR/html4/loose.dtd" doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN" indent="yes" />

and Finally! do make sure your XSLT output obeys the DOCTYPE  you have chosen.


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


Include XSL inside XSL

Sunday, May 4th, 2008 By Nikhil

If XML/XSL Transforms is your domian, then there are times when we want a peice of Dynamic code to be used library item(to be made re-usable). What I mean , probably could be made more clear with this example scenario.

Imagine you are creating a website (and using XML, XSL transfroms ofcourse) and most of the pages would have a Comments Module . Well! then either you copy or paste this code into every page template (which I dont have say, but make maintenance and rework a nightmare) or even better, you create an INCLUDE file which could be pulled in where ever you want it in your page(s)…
So HOW DO WE CREATE a XSL INCLUDE file and include it inside another XSL file? Here is how…

Just to make things clear … here is quick list of files that you would create … here , we will be including info about fruits and vegetables into a parent page called food.

1. food.xml – xml data file on which the transformation will be applied
2. food.xsl  -  main XSL file, which will transform our food.xml
3. inc_fruits.xsl – XSL include file that will render fruits data
4. inc_vegtables.xsl – XSL include file that will render vetetables data

I dont think I have explain much , the codes for above elements , will be self explanatory…

FOOD.XML


<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="food.xsl"?>
<food>
<date>July 2008</date>
<description>All about things we eat everyday</description>
<fruits type="tropical">
<item name="mango" moreinfo="http://www.mango.com">Mango is the king of fruits</item>
<item name="banana" moreinfo="http://www.banana.com">Banana once a day , keeps the doctor away</item>
<item name="orange" moreinfo="http://www.orange.com">Orange is the color and rich in vitamin C</item>
<item name="Papaya" moreinfo="http://www.papaya.com">Papaya - Hot when raw, cold when ripe</item>
</fruits>

<vegetables>
<item name="spinach" moreinfo="http://www.spinach.com">Spinach is full of iron</item>
<item name="asparagus" moreinfo="http://www.asparagus.com">Asparagus contains loads of vitamin D </item>
<item name="fenugreek" moreinfo="http://www.fenugreek.com">Fenugreek is rich in vitamin C</item>
</vegetables>
</food>


FOOD.XSL


<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:include href="inc_fruits.xsl" />
<xsl:include href="inc_vegetables.xsl" />
<xsl:template match="/">
<html>
<head>
<title>Title</title>
</head>
<body>
<h3><xsl:value-of select="/food/description" /></h3>
Modification Date : <xsl:value-of select="/food/date" />
<hr/>
<h5> About Fruits</h5>
<xsl:call-template name="about_fruits"/>

<hr/>
<h5> About Vegetables</h5>
<xsl:call-template name="about_vegetables"/>

<hr/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

 


INC_FRUITS.XSL

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="iso-8859-1" />
<xsl:template name="about_fruits">
<xsl:for-each select="/food/fruits/item/@*">
attribute name : <xsl:value-of select="name()"/> 
attribute value : <xsl:value-of select="."/> <br />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>


INC_VEGETABLES.XSL

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="iso-8859-1" />
<xsl:template name="about_vegetables">
<xsl:for-each select="/food/vegetables/item/@*">
attribute name : <xsl:value-of select="name()"/> 
attribute value : <xsl:value-of select="."/> <br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Download all the above files here (373 downloads)


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


Working with XML Node Attributes in XSLT

Friday, April 4th, 2008 By Nikhil

If you use XML and XSL, then you might have come across a time , when you have to play around with attributes and values of XML nodes in you XSL. They are loads of sites with long winded info about this, but none I found were brief and precise … This is NO XML/XSL TUTORIAL,but my attempt to put-together some sort of cheat list …

The sample XML that we will working with looks like this…

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="food.xsl"?>
<food>
<fruits type="tropical">
<item name="mango" moreinfo="http://www.mango.com">Mango is the king of fruits</item>
<item name="banana" moreinfo="http://www.banana.com">Banana once a day , keeps the doctor away</item>
<item name="orange" moreinfo="http://www.orange.com">Orange is the color and rich in vitamin C</item>
<item name="Papaya" moreinfo="http://www.papaya.com">Papaya - Hot when raw, cold when ripe</item>
</fruits>
</food>

So Lets begin transforming our above XML using XSL

Example 1 : Displaying value at a chosen Attribute

<xsl:value-of select="/food/fruits/item[@name='orange']" /><br />
to get more information about <a href="{/food/fruits/item[@name='orange']/@moreinfo}" target="new" ><xsl:value-of select="/food/fruits/item[@name='orange']/@name" /> </a>

HTML result will look like

Orange is the color and rich in vitamin C,
to get more information about <a href="http://www.orange.com" target="new">


Example 2 : Looping through and displaying all XML Attribute Names and their Values

<xsl:for-each select="/food/fruits/item/@*">
attribute name : <xsl:value-of select="name()"/>, 
attribute value : <xsl:value-of select="."/>  <br />
</xsl:for-each>

HTML result will look like


attribute name : name, attribute value : mango
attribute name : moreinfo, attribute value : http://www.mango.com
attribute name : name, attribute value : banana
attribute name : moreinfo, attribute value : http://www.banana.com
attribute name : name, attribute value : orange
attribute name : moreinfo, attribute value : http://www.orange.com
attribute name : name, attribute value : Papaya
attribute name : moreinfo, attribute value : http://www.papaya.com


Download all the above files here (374 downloads)



Watch this space, I’ll keep updating this with new findings…


get ExpressingIT News by Email Subscribe to ExpressingIT by Email or  Follow Me on Twitter


 Subscribe to ExpressingIT RSS
get ExpressingIT News by Email Subscribe to ExpressingIT by Email
 Follow Me on Twitter