Home arrow Perl Programming arrow Page 4 - XSL Transformations with Perl, Revisited

Transforming the Transformed - Perl

This article covers some API methods of the XML::XSLT module and shows you how to create a new XML file without needing to do any Perl programming. You will also learn how to transform a dynamically generated XML data structure.

  1. XSL Transformations with Perl, Revisited
  2. Objects in the mirror
  3. Different strokes
  4. Transforming the Transformed
By: Harish Kamath
Rating: starstarstarstarstar / 12
February 06, 2006

print this article



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">
        <stock symbol="KO" companyname="Coca-Cola">
        <stock symbol="GE" companyname="General Electric">
        <stock symbol="APPLE" companyname="Apple">

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

        <companyname>General Electric</companyname>

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>

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" />

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

# 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

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.


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. 

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: