22.7.3. Discussion
XML::LibXSLT is built on the fast and powerful
libxslt library from the GNOME project. To
perform a transformation, first build a stylesheet object from the
XSL source and then use it to transform an XML file. If you wanted to
(for example, your XSL is dynamically generated rather than being
stored in a file), you could break this down into separate steps:
use XML::LibXSLT;
use XML::LibXML;
my $xml_parser = XML::LibXML->new;
my $xslt_parser = XML::LibXSLT->new;
my $xml = $xml_parser->parse_file($XML_FILENAME);
my $xsl = $xml_parser->parse_file($XSL_FILENAME);
my $stylesheet = $xslt_parser->parse_stylesheet($xsl);
my $results = $stylesheet->transform($xml);
my $output = $stylesheet->output_string($results);
$stylesheet->output_fh($FILEHANDLE);
It's possible to pass parameters to the transformation engine. For
example, your transformation might use parameters to set a footer at
the bottom of each page:
$stylesheet->transform($xml, footer => "'I Made This!'");
The strange quoting is because the XSLT engine expects to see quoted
values. In the preceding example, the double quotes tell Perl it's a
string, whereas the single quotes are for the XSLT engine.
use strict;
use XML::LibXML;
use XML::LibXSLT;
my $xml_parser = XML::LibXML->new;
my $xslt_parser = XML::LibXSLT->new;
sub match_names { ... } # as in example 22-10
$xslt_parser->register_function("urn:test", "match_names", \&match_names);
my $dom = $xml_parser->parse_file('test.xml');
my $xslt_dom = $xml_parser->parse_file('test.xsl');
my $xslt = $xslt_parser->parse_stylesheet($xslt_dom);
my $result_dom = $xslt->transform($dom);
print $result_dom->toString;
Use closures to let XSLT access to Perl variables, illustrated here
with an Apache request object:
$xslt->register_function("urn:test", "get_request",
sub { &get_request($apache_req,@_) } );