Perl
  Home arrow Perl arrow Page 4 - XSL Transformation with Perl
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PERL

XSL Transformation with Perl
By: Harish Kamath
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2005-07-25


    Table of Contents:
  • XSL Transformation with Perl
  • Getting started
  • My Investment Portfolio
  • Demystifying the XML::XSLT processor
  • Error Management

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    XSL Transformation with Perl - Demystifying the XML::XSLT processor
    ( Page 4 of 5 )

    The XML document in the first example listed only one stock in my sample portfolio, but things are a bit more complicated in real life. Consider the next XML file that contains several stocks in a single portfolio -- after all, no one likes to put all their eggs into one basket!

    <?xml version="1.0"?>
    <portfolio>
        <name>The Bull Pit</name>
     <stock>
          <symbol>KO</symbol>
          <companyname>Coca-Cola</companyname>
          <quantity>500</quantity>
          <lasttradedprice>14.00</lasttradedprice>
         </stock>
         <stock>
          <symbol>GE</symbol>
          <companyname>General Electric</companyname>
          <quantity>2400</quantity>
          <lasttradedprice>20.00</lasttradedprice>
         </stock> 
         <stock>
          <symbol>APPLE</symbol>
          <companyname>Apple</companyname>
          <quantity>3500</quantity>
          <lasttradedprice>14.00</lasttradedprice>
         </stock> 
    </portfolio>

    Take a look at the accompanying XSLT style sheet. I’ve updated the code to make it modular in its approach. You’ll notice that each element in the XML file has its very own <xsl:template> giving you greater flexibility. Also, note the use of ASCII characters in the "portfolio" and "lasttradedprice" templates to generate a fancy output, as shown later.

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

    <xsl:template match="/portfolio">
    Portfolio Name: <xsl:value-of select="name" /> 
    ========================================
    <xsl:apply-templates select="stock"/>
    </xsl:template>

    <xsl:template match="stock">
    <xsl:apply-templates select="companyname"/>
    <xsl:apply-templates select="symbol"/>
    <xsl:apply-templates select="quantity"/>
    <xsl:apply-templates select="lasttradedprice"/>
    </xsl:template>

    <xsl:template match="companyname">
    Company Name:<xsl:value-of select="." />
    </xsl:template>

    <xsl:template match="symbol">
    Symbol: <xsl:value-of select="." />
    </xsl:template>

    <xsl:template match="quantity">
    Quantity:<xsl:value-of select="." />
    </xsl:template>

    <xsl:template match="lasttradedprice">
    Last Traded Price:<xsl:value-of select="." />
    ---------------------------------------------
    </xsl:template>

    </xsl:stylesheet>

    Next, I have the glue that brings the two together: the Perl script. I’ve made some minor updates to the script from the first example. I will explain more about these changes after you have reviewed the next code listing and the subsequent output.

    # !/usr/bin/perl

    # import required modules
    use XML::XSLT;

    # define local variables
    my $xslfile = "portfolio.xsl";
    my $xmlfile = "portfolio.xml";

    # create an instance of XSL::XSLT processor
    my $xslt = XML::XSLT->new ($xslfile, warnings => 1, debug => 1);

    # transforms the XML file using the XSL style sheet
    $xslt->transform ($xmlfile);

    # send to output
    print $xslt->toString;

    # free up some memory
    $xslt->dispose();

    … and the output.

    Portfolio Name: The Bull Pit 
    ========================================

    Company Name:Coca-Cola
    Symbol: KO
    Quantity:500
    Last Traded Price:14.00
    ---------------------------------------------

    Company Name: General Electric
    Symbol: GE
    Quantity:2400
    Last Traded Price:20.00
    ---------------------------------------------

    Company Name: Apple
    Symbol: APPLE
    Quantity:3500
    Last Traded Price:14.00
    ---------------------------------------------

    Yes, I have omitted the huge amounts of text that may have scrolled across your screen. The reason for this "strange" behavior will be unraveled in the next few lines as I proceed to de-mystify the updated Perl script.

    As you can see above, there are no changes to the first few lines of the script. Next, take a look at the following code snippet:

    // snip

    # create an instance of XSL::XSLT processor
    my $xslt = XML::XSLT->new ($xslfile, warnings => 1, debug => 1);

    # transforms the XML file using the XSL style sheet
    $xslt->transform ($xmlfile);

    # send to output
    print $xslt->toString;

    // snip

     

    Note the use of the "warnings" and "debug" properties in the new() method. As the names suggest, these instruct the XSLT processor to output useful -- but verbose, as is evident from the output that scrolled across your screen -- debug information. I have turned on both features by setting the value of the properties to "1", and I recommend that you do the same to help rectify annoying errors, inevitable during the initial stages of any project.

    Next, I have opted for the transform() method instead of the serve() method, used earlier. The most significant difference between the two methods is the return value -- the latter, as we have already seen, returns a string that can print()ed on the screen without much fuss. It is not so with the transform() method; this returns an XML DOM object. Don’t take my word for it; print the return value and you should see something like this on your screen.

    XML::DOM::DocumentFragment=ARRAY(0x1eeea9c)
     

    Not pleasant at all. But there is no reason to despair; the XML::XSLT processor is equipped with a handy "toString" property that spits out the result of the transformation in a human-friendly format -- as is evident from the output, listed above.

    If you’re wondering why you would want another XML DOM object, the reason  is simple: it is likely that the result of the transformation could serve as the input to another process that is expecting an XML file. In such a case, it would be handy to have a DOM object with the XML structure in memory.



     
     
    >>> More Perl Articles          >>> More By Harish Kamath
     

       

    PERL ARTICLES

    - More Perl Bits
    - Perl, Bit by Bit
    - Basic Charting with Perl
    - Using Getopt::Long: More Command Line Option...
    - Command Line Options in Perl: Using Getopt::...
    - Web Access with LWP
    - More Templating Tools for Perl
    - Site Layout with Perl Templating Tools
    - Build a Perl RSS Aggregator with Templating ...
    - Looping, Security, and Templating Tools
    - Perl: Bon Voyage Lists and Hashes
    - Templating Tools
    - Perl: Number Crunching
    - Perl Debuggers in Detail
    - Debugging Perl





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT