Perl
  Home arrow Perl arrow Page 4 - XSL Transformation with Perl
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
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: 5 stars5 stars5 stars5 stars5 stars / 8
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    PCmover - $15 Off with Coupon Code CJPH7Q

    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

    - Perl: A Continuing Look at Hashes and Multid...
    - Perl: Another Round with Hashes
    - Perl Hashes
    - Perl Lists: A Final Look at List::Util
    - Perl Lists: Utilizing List::Util
    - Perl Lists: The Split() Function
    - SQL and CGI with Perl and DBI
    - Perl Lists: More Functions and Operators
    - SELECT Queries and Perl
    - Perl Lists: More on Manipulation
    - Creating a Database with Perl and DBI
    - Perl: Sailing the List(less) Seas
    - Perl and DBI
    - Perl: Concatenating Text and More
    - Perl Text: Quoting Without Quote Marks

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway