XSL Transformations with Perl, Revisited - Objects in the mirror
(Page 2 of 4 )
All examples, thus far, use a XML file as an input source to the XSLT processor. However, this may not always be true. Consider the following example that provides a XML DOM object as input:
# !/usr/bin/perl
# import required modules
use XML::XSLT;
use XML::DOM;
# define local variables
my $xslfile = "portfolio.xsl";
my $xmlfile = "portfolio.xml";
# create an instance of the DOM object
my $xml_parser = new XML::DOM::Parser;
my $xml_dom = eval { $xml_parser->parsefile ($xmlfile) };
# 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 ($xslfile, warnings => 1, debug
=> 0) };
# some more error handling here ...
if ($@) {
die("Sorry, Could not create an instance of the XSL
Processor using $xslfile.\n");
}
# transform the XML DOM object using the XSL style sheet
eval { $xslt->transform ($xml_dom) };
# ... and here
if ($@) {
die("Sorry, Could not transform XML file, $xmlfile.\n");
}
# send to output
print $xslt->toString;
# free up some memory
$xml_dom->dispose();
# throws error
# $xslt->dispose();
Once again, I've reused the "portfolio.xml" XML document as well as the "portfolio.xsl" XSLT style sheet, and as you may have guessed, the output remains the same. Only the implementation has been updated.
It is said that the proof of the pudding is in the eating, so let's review the code listing closely to understand what's different!
For starters, I've imported two Perl modules, XML::XSLT and XML::DOM. The latter allows me to create an XML::DOM object which I pass to the XSLT processor for further processing, as seen below.
// snip
# create an instance of the DOM object
my $xml_parser = new XML::DOM::Parser;
my $xml_dom = eval { $xml_parser->parsefile ($xmlfile) };
// snip
After creating a new instance of the DOM parser, I call the parsefile() method. This returns an XML::DOM object containing the XML document passed as input.
The rest of the code listing is self-explanatory. I pass the XML::DOM object as input to the XSLT processor. However, this change of input does not alter the behavior of the transform() method. It proceeds to apply the XSL transformations from the style sheet to the XML structure (represented by the DOM object) and voila -- I have the required output.
Next: Different strokes >>
More Perl Articles
More By Harish Kamath