Perl
  Home arrow Perl arrow Page 4 - XSL Transformations with Perl, Revisit...
Dev Shed Forums 
Administration  
AJAX  
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 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
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 Transformations with Perl, Revisited
By: Harish Kamath
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 11
    2006-02-06

    Table of Contents:
  • XSL Transformations with Perl, Revisited
  • Objects in the mirror
  • Different strokes
  • Transforming the Transformed

  • 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    XSL Transformations with Perl, Revisited - Transforming the Transformed


    (Page 4 of 4 )

    Nobody's perfect. And, I am "Nobody."

    Jokes aside, it is likely that the XML data available is not suitable for my requirements. In such situations, I can keep whining about it or rush to author a Perl script to resolve the problem, which is exactly what I have done below. Read on.

    Consider the following XML file.

    <?xml version="1.0"?>
    <portfolio name="The Bull Pit">
        <stocks>
            <stock symbol="KO" companyname="Coca-Cola">
                <quantity>500</quantity>
                <currenttradedprice>14.00</currenttradedprice>
                <previoustradedprice>14.00</previoustradedprice>
            </stock>
            <stock symbol="GE" companyname="General Electric">
                <quantity>2400</quantity>
                <currenttradedprice>25.00</currenttradedprice>
                <previoustradedprice>24.25</previoustradedprice>
            </stock> 
            <stock symbol="APPLE" companyname="Apple">
                <quantity>3500</quantity>
                <currenttradedprice>35.00</currenttradedprice>
                <previoustradedprice>38.00</previoustradedprice>
            </stock> 
        </stocks>
    </portfolio>

    I've already shown you how to convert the above XML to another format that looks something like this:

    <stocks>
        <stock>
            <symbol>KO</symbol>
            <companyname>CocaCola</companyname>
        </stock>
        <stock>
            <symbol>GE</symbol>
            <companyname>General Electric</companyname>
        </stock>
        <stock>
            <symbol>APPLE</symbol>
            <companyname>Apple</companyname>
        </stock>
    </stocks>

    Useful, but remember the XML-phobic stock analyst about whom I referred to in the first part: he would be really happy if the output looked something like this.

    Stocks in my portfolio
    ============================================

    Company Name: Coca-Cola

    Symbol: KO

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

    ... and so on.

    As you might have guessed, I'll require two style sheets in this example. The first one, listed below, has been repeated for the sake of continuity. As I've shown you earlier, it creates a new XML structure from an existing one.

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/portfolio/stocks">
    <xsl:element name="stocks">
    <xsl:for-each select="stock">
    <xsl:element name="stock">
    <xsl:element name="symbol"><xsl:value-of select="@symbol" /></xsl:element> <xsl:element name="companyname"><xsl:value-of select="@companyname" /></xsl:element> </xsl:element> </xsl:for-
    each> </xsl:element>
    </xsl:template>
    </xsl:stylesheet>

    Next, I have another XSL style sheet with instructions to transform the interim XML output into the required analyst-friendly output.

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/stocks">
    Stocks in my portfolio
    <xsl:for-each select="stock"> ============================================
    Company Name: <xsl:value-of select="companyname" />
    Symbol: <xsl:value-of select="symbol" />
    --------------------------------------------
    </xsl:for-each>
    </xsl:template>
    </xsl:stylesheet>

    Finally, here is the Perl script that brings about this back-to-back transformation:

    # !/usr/bin/perl

    # import required modules
    use XML::XSLT;
    use XML::DOM;

    # define local variables
    my $xslfile1 = "portfolio1.xsl"; # for first transformation
    my $xslfile2 = "portfolio2.xsl"; # for second transformation
    my $xmlfile = "portfolio.xml";

    # check for errors ...
    if ($@) {
           
    die("Sorry, Could not parse the XML file,
    $xmlfile.\n"); }

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

    # some more error handling here ...
    if ($@) {
           
    die("Sorry, Could not create an instance of the XSL
    Processor using $xslfile1.\n"); }

    # transform the XML file using the XSL style sheet
    # store output as XML DOM object
    eval { $xslt->transform($xmlfile) };

    # ... and here
    if ($@) {
           
    die("Sorry, Could not transform XML file,
    $xmlfile.\n"); }

    # store interim XML output in a string variable
    $xml_string = $xslt->toString;

    # clear up memory
    $xslt->dispose();

    # reload XSL::XSLT processor with new style sheet
    $xslt = eval { XML::XSLT->new ($xslfile2, warnings => 1, debug =>
    0) };

    # error handling here ...
    if ($@) {
           
    die("Sorry, Could not create an instance of the XSL
    Processor using $xslfile2.\n"); }

    # transform the XML string in memory using the new XSL style sheet eval { $xslt->transform($xml_string) };

    # ... and here
    if ($@) {
           
    die("Sorry, Could not transform XML::DOM object.
    $@\n"); }

    # send to output
    print $xslt->toString;

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

    Now, execute this script to view the following output on the screen.

    Stocks in my portfolio ============================================

    Company Name: Coca-Cola
    Symbol: KO

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

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

    Company Name: General Electric
    Symbol: GE

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

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

    Company Name: Apple
    Symbol: APPLE

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

    Now it's time to dissect the script. Initially, I defined an additional variable to store the name of the second style sheet. Next, I instantiated an XML::XSLT object with the first style sheet, transformed the input XML file, and stored the output in the "$xml_string" variable.

    At this point, I'll admit that things didn't quite go according to plan. Initially, I wanted to demonstrate the open_xsl() method that allows me to load a new style sheet at run-time. Unfortunately, it did not work as advertised; the associated Perl package threw an error that caused my script to stop execution. As I said earlier, nobody's perfect -- and the XML::XSLT module is definitely NOT nobody!

    So, time for Plan B. Here, I create another XML::XSLT object, load the second style sheet, pass the "$xml_string" variable as input, transform the interim XML data and render the output -- a simple and easy-to-understand listing of all the stocks in the portfolio -- on the screen.

    Conclusion

    This brings me to the conclusion of the two-part series on XSL transformations with Perl.

    Let's quickly review the topics introduced: first, I demonstrated the use of the open_xml() and process() methods; together they provide us with one more mechanism to transform XML documents.

    Next, I showed how to transform a XML data structure, available in the form of an XML::DOM object. This comes in handy when you want to perform intermediate transformations and avoid the creation of temporary XML files on the server.

    Subsequently, I demonstrated the capabilities of the Perl-based XSLT processor by showing you how to create a new XML data structure from scratch using the <xsl:element> instruction.

    The final example demonstrated the concept of transforming dynamic XML created in an earlier XSL transformation. Unfortunately, this example also highlighted the drawbacks of the XML::XSLT module, leaving me with no option but to implement a cheeky workaround to get the job done.

    I'll admit that the XML::XSLT module does not allow a Perl programmer to fully leverage the capabilities of XSL transformations as many features (that are part of the official XSL transformations specification) are not implemented by the module. However, it does provide Perl novices with the required tools to initiate their understanding of XSL transformations in their favorite language.

    To summarize, I have listed a couple of URLs for XSL transformations tutorials on the Internet for quick reference:

    XSLT Tutorial at Zvon.org - http://www.zvon.org/xxl/XSLTutorial/Books/Book1/

    XSL Family at W3C - http://www.w3.org/Style/XSL/

    This brings me to end of the series. Till next time, take care. 


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

     

       

    PERL ARTICLES

    - Perl: More on Lists and Hashes
    - Perl: Dimensional Lists
    - 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





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