XSLT  in J2EE/JAX &  ASP.Net

         (published in DeveloperIQ..October-2004)

R.S.RAMASWAMY

(rs.ramaswamy@gmail.com)

 

       This is a 4 part tutorial

 

 

         XSLT BASICS & DEMOS IN MICROSOFT BROWSER .xslt.htm

 

         XSLT  IN  DOTNET  PLATFORM. xslt2.htm            

 

         XSLT PROCESSING USING XALAN IN JAVA  xslt3.htm   

 

       XSLT  IN JSP  USING BEAN    xslt4.htm           

 

 

 

                               PART-1

                               ------

           XSLT BASICS & DEMOS IN MICROSOFT BROWSER

         =======================================

 

 

    In the previous instalments(july & august ,2004), we had seen how jdk1.4 simplifies XML processing in java by incorporating JAXP1.1 in Jdk itself.

    We saw how XML processing can be done by using DOM , SAX and JDOM. However, there is yet another method known as XSLT (Extensible Style-sheet Transformation).

Xalan  is the most well-known XSLT processor and is now available from Apache Software Foundation.This is the default XSLT processor in jdk1.4.

 In this part of the tutorial, we will acquaint ourselves with XSL terminology and techniques , a standard maintained by W3C (WorldWideWeb Consortium).

 

    XML technologies like DOM,SAX and XSLT are important not only for J2EE programmers but ASP.net and Perl/PHP/Python programmers as well.

 

In fact, the entire DotNet framework has been built with easy XML transformations in mind, from the ground-up.Microsoft has been one of the main driving forces behind the adoption of XML and had the foresight to incorporate very powerful support for XML and XSLT in Internet-Explorer browser, long back.Netscape followed suit only later.Someone lamented in the web forum that the OSF community 'won the battle but lost the war' by conceding leadership to Microsoft in browser technologies.Ultimately it is the mind-share of the end-user that decides the issue . SOAP (Simple Object Access Protocol) also is a standard , proposed and promoted by Microsoft, though it has now become a public standard.

 

( DON BOX of Developmentor and Dr.Gopal Kakivaya of Microsoft labs were the lead authors of SOAP). As mentioned in the previous instalment of this tutorial, this could even lead us sometimes to identify XML too closely with  ready-made xml-processing in Microsoft browser (client-side).Fortunately for open-source adherents, Mozilla browser , has caught up with Internet Explorer in its xslt capabilities.Netscape6 also  offers similar facilities now.

    [However, the advent of server-side xsl transformation, has made browser-side xslt 'not-so-vital', now.]

 

    Jon Bosak of Sun Micro-system was one of the lead- persons in the creation of XML specifications. And IBM has done its own share by donating Lotus-XSLT Processor  to Apache Foundation.(Xalan is based on this).Thus, all the leading corporates have played their role in developing XML standards and tools.Individuals like Michael  Kay (SAXON xslt processor) also have contributed.As XML-WebService unifies all languages and platforms, it will be short-sighted if we persist in old-ways of thinking, pitting one company  against another, though each has its own merits and demerits.We will adopt each technology by its suitability for a given requirement  , rather than by its source of creation.’Horses for the Courses! ‘, as they say.

 

 Granting that XML is 'platform and language neutral data' and Java is 'platform-neutral language' ,the third leg of the tripod  is missing. How do we translate XML data into other forms?That is where XSLT,  appears.This potential for transformation is what sets XML apart from other data-formats like HTML, PDF and PostScript.

 

         Web applications must support a number of different types of clients such as HTML browsers, WAP browsers and other types for wireless clients. It is not realistic to create the data specifically for each client. The better method is to have a single XML file but distribute this to different clients , after suitable 'transformation'. ( that explains why we are speaking of TrAX ..' Transformation API for XML').

 

   Looking at a possible scenario in j2ee environment, the business-logic is encapsulated in an EJBean. The EJBean is called by either a servlet or jsp.

 

The data returned by the EJBean is converted into  XML form.Ready-made software (freeware ,even) is available for this purpose. Even otherwise, it can  be done by us programmatically . It is always easy to convert a relational table into its xml equivalent . But , to convert an xml file in hierarchial data form into a relational table is admittedly difficult and clumsy.Luckily for programmers, Enterprise data so far is mainly in Relational databases.

 

  Once the query result is available in xml form, it can be sent for display in different formats,suitable  for  standard web-browsers and mobile clients. For this purpose, we can use different style-sheets.(XSL stands for Extensible style-sheet Language).

 

    XSL is split up into two different specifications.

     a) XSL-FO   ( Formatting Objects)

     b) XSLT      (Transformation)

   XSL-FO is purely about presentation while XSLT is presentation & transformation. XSLT is considered by many experts as the most important part of XML initiative.And 'Cocoon', a famous open-source & free software from Apache is entirely based on XSLT.

 

         It is customary to speak of clear separation of business-logic and presentation. Thus, in a web application, JSP is recommended ,rather than a pure servlet, because it is easier to  encapsulate the business-logic in a jsp-bean and minimize the code in a dynamically-created page, leaving the job of suitable presentation to page-designers, who need not know Java language and programming atall.Such division of labour , is seen to improve the quality of the result and also make maintenance easier.

 ----

    XML & XSLT combination goes one step further. Here, we have clean separation between logic, data and presentation.

   a)  Ejbean  deals with the logic

   b)  data is in XML

   c)  presentation is taken care of,  by XSLT.

 

    Is XSLT then all about transformation for presentation only? Not atall!XSLT can be used like SQL. We can use xslt to query, sort and  modify,the xml data itself.Thus it is not a mere presentation technology but a data-extraction and data-manipulation technology as well.

 

     Actually, XSLT is a PROGRAMMING LANGUAGE concealed  and expressed in XML syntax.  Among programming languages, there are  many types.Unlike languages like C, C++, Java , Pascal etc which are known as 'Imperative Languages', XSLT belongs to the 'functional languages' group.Its approach has some resemblance to languages like Lisp/ Scheme. As it is expressed in familiar html/xml syntax , it is deceptively simple. From another perspective, we can think of XSLT as being similar to SQL of database queries, where we simply state what we want and do not dictate how it should be done.

 

 

      Let us now consider a simple example. We are having an XML file named 'students.xml'.

( please remember , that XML is case-sensitive).Just to get familiar with the idea, we will consider displaying this xml file after transforming it by using a style-sheet. We are using Internet Explorer-6 and using its built-in xslt capabilities.

 

[ The  emphasis in this tutorial is not so much on in-depth treatment of XSLT  but on implementing  it in J2EE & ASP.net environments.]

 

      The students.xml file is given below.

   ***********************************************

//  students.xml

<?xml version="1.0"?>

 

<students>

    <student>

         <name>Thomas</name>

         <place>Delhi</place>

         <number>1111</number>

         <mark>78</mark>

     </student> 

 

    <student>

         <name>David</name>

         <place>Bombay</place>

         <number>2222</number>

         <mark>90</mark>

     </student>

 

    <student>

         <name>Mathew</name>

         <place>Bangalore</place>

         <number>3333</number>

         <mark>92</mark>

     </student>

    

    <student>

         <name>John</name>

         <place>Madras</place>

         <number>4444</number>

         <mark>72</mark>

     </student>

    

</students>

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

   The following style-sheet is used for

displaying the above xml file.

 

//   xsl1.xsl

==============

<?xml version="1.0"?>

<xsl:stylesheet

 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

 

<xsl:template             match="/">

 

  <html>

    <body>

      <table border="2"     bgcolor="yellow">

         <tr>

            <th>Name</th>

            <th>Place</th>

            <th>Number</th>

            <th>Mark</th>

          </tr>

 

     <xsl:for-each        select="students/student">

       <tr>

 <td><xsl:value-of    select="name"/>     </td>

 <td><xsl:value-of    select="place"/>    </td>

 <td><xsl:value-of   select="number"/>   </td>

 <td><xsl:value-of   select="mark"/>     </td>

       </tr>

     </xsl:for-each>

 

     </table>

   </body>

 </html>

</xsl:template>

</xsl:stylesheet>

 

 

 

We are having  students.xml  and  xsl1.xsl in  ‘C:\xslt’   folder.  let us now view   ‘c:\xslt\students.xml’  in InternetExplorer-6.We will get a display of the file in xml format with tree structure,just as the original xml file.Let us now make a reference to xsl1.xsl in the students.xml  file and rename it as xslstudents.xml

The modified file xslstudents.xml is shown below.

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

// xslstudents.xml

 

<?xml version="1.0"   ?>

<?xml-stylesheet   type="text/xsl"   href="xsl1.xsl" ?>

 

<students>

    <student>

         <name>Thomas</name>

         <place>Delhi</place>

         0<number>1111</number>

         <mark>78</mark>

     </student>

 

   //  as before

 

   

    <student>

         <name>John</name>

         <place>Madras</place>

         <number>4444</number>

         <mark>72</mark>

     </student>

 

   

</students>

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

If we view c:\xslt\xslstudents.xml in IE6,

 we get the data displayed as html page with table.

 

Name

Place

Number

Mark

Thomas

Delhi

1111

78

David

Bombay

2222

90

Mathew

Bangalore

3333

92

John

Madras

4444

72

 

So, we have invoked the xml file with ‘built-in’ style sheet reference  and viewed it in IE6.

Just a bit of explanation is in order.

The declaration   MUST assign a version number.

The XSLT schema location is at :

'http://www.w3.org/1999/XSL/Transform' & is assigned as namespace. It is purely an internal reference and we don't have to be connected to the internet to use the xsl file which uses this namespace reference!But, we should type this without the slightest mistake , especially regarding case.

-- The for-each tag  has now crept into jdk also and so should be familiar to asp.net and jdk coders. It is a kind of looping. We are asking the code to select and display in  table cells the values of name, place, number and mark. for each  in 'students/student'  path.There comes the other piece of the specification, named XPath. It can be thought of as similar to  the familiar  file hierarchy

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

We will now see four more examples and the resulting display.

xsl2.xsl

 

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

 

<xsl:template match="/">

  <html>

    <body>

sorting in ascending order by name of the student.

      <table border="2" bgcolor="cyan">

      

     <xsl:for-each        select="students/student">

 <xsl:sort  select="name"

        order="ascending"    />           

    

       <tr>

   <td><xsl:value-of        select="name"/>     </td>

 

       etc:  ( as before )

Result

======

    

David

Bombay

2222

90

John

Madras

4444

72

Mathew

Bangalore

3333

92

Thomas

Delhi

1111

78

 

 

 

 

   xsl3.xsl  

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

 

<xsl:template match="/">

  <html>    <body>

   SORTING BY name   (Descending)

      <table border="2" bgcolor="tan">

        

     <xsl:for-each        select="students/student">

 

     <xsl:sort select="name"

             order="descending"   />          

    

       <tr>

   <td><xsl:value-of        select="name"/>     </td>

 

           etc...( as before)

result

======       

 

Thomas

Delhi

1111

78

Mathew

Bangalore

3333

92

John

Madras

4444

72

David

Bombay

2222

90

 

===============================================

 

 

 

   xsl4.xsl    

 

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

 

<xsl:template match="/">

  <html>

    <body> 

      <table border="2" bgcolor="pink">     

     <xsl:for-each        select="students/student">

  <xsl:sort   select="mark"

          data-type="number" 

               order="ascending"  />            

    

       <tr>

    <td><xsl:value-of        select="name"/>     </td>

        

            etc.....   ( as before)

 

result

=======

 

John

Madras

4444

72

Thomas

Delhi

1111

78

David

Bombay

2222

90

Mathew

Bangalore

3333

92

 

===============================================

 

 

    xsl5.xsl   

 

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

 

<xsl:template match="/">

  <html>    <body>

    

     <xsl:for-each        select="students/student">

   

  <xsl:if           test="name='Mathew' "   >

     <h1>  HELLO!...MATHEW!   </h1>

         </xsl:if>  

     </xsl:for-each>        

 </body>  </html>

 

 result

=======

    HELLO! MATHEW

 

In the above examples, the xsl reference was hard-coded inside the xml file. We can avoid it and use javascript or vbscript to supply the required xsl file REFERENCE.This technique is more versatile.The code for  manipulation using javascript  follows:

--

<html>

<body>

<form    name='form1'>

<select   name='combo1'>

    <option   value="style1">style1

    <option   value="style2">style2

</select>

<input   type=button   value='confirm'  onclick='job1()' >

 

</form>

 

<script   language="javascript">

function  job1()

{

s=form1.combo1.value

alert(s)

 

if(s=="style1"){s="xsl1.xsl";}

if(s=="style2"){s="xsl2.xsl";}

 

xml = new ActiveXObject("Microsoft.XMLDOM");

xml.async=false

xml.load("students.xml")

 

xsl=new ActiveXObject("Microsoft.XMLDOM")

xsl.async=false

xsl.load(s)

 

document.write(xml.transformNode(xsl))

}

 

</script>

</body>

</html>

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

There is nothing much very difficult to follow in this example, except 'xsl.async=false'.Real life xml files can be very large and may take a long time to get down-loaded.

 We are using asynchronous loading technique here.As we are loading from a local file, it does not make much difference.

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

   As we are writing code for Microsoft IE-6, we may as well use vbscript and get away from case-sensitive javascript.We should carefully note how xml & xsl objects are defined in vbscript.The vbscript version follows:

----

<html>

<body>

<form name=form1>

<select   name='combo1'>

    <option   value="style1">style1

    <option   value="style2">style2

</select>

<input type=button onclick=job1() value="click">

</form>

 

<script language="vbscript">

sub job1()

 

  s=form1.combo1.value

  if s="style1" then s="xsl1.xsl"

  if s="style2" then s="xsl2.xsl"

 

 set xml=createobject("Microsoft.XMLDOM")

  xml.async=false

  xml.load("students.xml")

 

 set xsl=createobject("Microsoft.XMLDOM")

  xsl.async=false

  xsl.load(s)

 

  document.write(xml.transformNode(xsl))

end sub

</script>

 

</body>

</html>

 

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

 

What we have done can be termed as 'local transformation' because both the xml file and the xsl file were obtained from local hard-disk.But the same technique can be used for Client-side transformation.

 

The XML file and the associated XSL files are placed in the web-server. If there is a reference to XSL file built into the XML file, the browser automatically makes another trip to the webserver to get the XSL file and then use it.But , this is possible only in latest browsers like IE6 ,Netscape-6 etc.  It is not correct for us to assume that all the clients are having such modern browsers. Some may

have wap-browsers and this technique will fail.Anyway, we placed xslstudents.xml & xsl1.xsl in d:\inetpub\wwwroot and typed the URL as 'http://localhost/xslstudents.xml'.

( Any web-server will do!...because, processing is done by InternetExplorer-6.)

We got correct result ( a table with yellow background). 

-------

   We have thus seen 'local transform' and 'client-side transform',However, the correct method is 'Server-side' transformation.'We can do such server-side transformation , if our server is Microsoft-Information-Server-5.We must carefully note the version number. IIS4 does not offer full xslt features. This is explained in part-2 of this tutorial instalment.

 

 

  Continued in XSLT IN   DOTNET