Using XSLT from Perl

Problem

You have a problem that is more appropriately solved in Perl, but would be easier with a pinch of XSLT.

Solution

There are several choices for embedding XSLT in Perl. XML::LibXSLT and XML::LibXML are Perl frontends to the functionality of GNOME library’s SAX and XSLT processors. The following example, borrowed from Erik T. Ray’s and Jason McIntosh’s Perl and XML (O’Reilly, 2002), shows a Perl program that batch-processes several XML files with a single XSLT script, compiled once:

use XML::LibXSLT;
use XML::LibXML;
   
# the arguments for this command are stylesheet and source files
my( $style_file, @source_files ) = @ARGV;
   
# initialize the parser and XSLT processor
my $parser = XML::LibXML->new(  );
my $xslt = XML::LibXSLT->new(  );
my $stylesheet = $xslt->parse_stylesheet_file( $style_file );
   
# for each source file: parse, transform, print out result
foreach my $file ( @source_files ) {
  my $source_doc = $parser->parse_file( $source_file );
  my $result = $stylesheet->transform( $source_doc );
  print $stylesheet->output_string( $result );
}

Parameters to the stylesheet can be passed in as a Perl hash, as shown in the following code:

               #Similar code from previous example has been elided.
   
my %params = {
               param1 => 10,
    param2 => 'foo',
} ;
   
foreach my $file ( @source_files ) {
  my $source_doc = $parser->parse_file( $file );
  my $result = $stylesheet->transform($source_doc, %params);
  print $stylesheet->output_string( $result );
}

Passing parameters to from Perl to the stylesheet ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.