Tuesday, September 13, 2011

Two XSLT transformation in javascript


Introduction.

In order to execute XSLT transformation in IE two different javascript methods can be done.
In this article I would like explain how to use each of the javascript method.

Setup

So for a start I created XML and XSL that I will show transformation.

XML Example
<?xml version="1.0"?>
<products>
<product href="http://www.playfield.com/text">
      <name>Playfield Text</name>
      <price currency="usd">299</price>
      <description>Faster than the competition.</description>
      <version>1.0</version>
   </product>
</product>


XSLT Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="no"/>
   <xsl:template match="/products">
        <table>
          <tr class="header">
             <td>Name</td>
             <td>Price</td>
             <td>Description</td>
          </tr>
          <xsl:apply-templates/>
        </table>
</xsl:template>
<xsl:template match="product[position() mod 2 = 1]">
   <tr class="odd">
      <td><xsl:value-of select="name"/></td>
      <td><xsl:value-of select="price"/></td>
      <td><xsl:value-of select="description"/></td>
   </tr>
</xsl:template>
<xsl:template match="product">
   <tr class="even">
      <td><xsl:value-of select="name"/></td>
      <td><xsl:value-of select="price"/></td>
      <td><xsl:value-of select="description"/></td>
   </tr>
</xsl:template>
</xsl:stylesheet>


The first method.

The first method that can trasform XSLT is to use "transformNode"
method of Microsoft.XMLDOM object.

Please see below the code

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


   xml.load("data.xml");
   xslt.load("transformxsl.xml");
   var output = xml.transformNode(xslt);

The code is pretty simple. Need to define a two XMLDom object and invoke transform method.

The second method.

The second method is to use with XSLTemplate.

    var xml = new ActiveXObject("Microsoft.XMLDOM");
    var xslt = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
   
    xml.load("data.xml");
    xslt.load("transformxsl.xml");
   
   var processor   = new ActiveXObject("Msxml2.XSLTemplate");
   processor.stylesheet = xslt;

   var objXSLTProc = processor.createProcessor();
   objXSLTProc.input = xml;
   objXSLTProc.transform();
   var output  = objXSLTProc.output;


The object is to load XSLT need to be created from FreeThreadedDOMDocument.
The transformation is done by object created from Msxml2.XSLTemplate.
Afterwords need to invoke transform method.

Summary

We looked in two different approaches of XSLT transformatiion.
On my next article, we will check which is the best solution.
Please follow my next article to see the result.




No comments:

Post a Comment