Chapter 16. XML and Perl
There is no doubt about it, XSLT is programming language. It is a language enabling you to read XML and output text, whether it be in the form of XML or not. But computing tasks involve more than the output of text. There are databases, outside applications and data sets, hardware, and of course human interfaces to take into account. In the big scheme of things XSLT provides limited functionality. There is the need for more all-inclusive programming techniques. The use of Perl is such a techique. It is an ex- cellent scripting language that can glue together the necessary components for a more complete solution. Without getting involved in any programming religious wars, this section outlines a few examples of how you can use Perl to manipulate XML.
A simple XSLT transformer
The functions in libxml2 and libxslt, the C libraries underlying xmllint and xsltproc, have been made available to Perl scripts through two modules: XML::LibXML and XML::LibXSLT. Considering this it is possible to create the Perl equivelent of xsltproc. Here is the outline of such an application. It is saved in the workshop's distribution as bin/xsltproc.pl:
require the necessary modules
use strict; use XML::LibXML; use XML::LibXSLT;
e = $ARGV;
my $parser my $xslt
= XML::LibXML->new; = XML::LibXSLT->new;
# parse the
my $stylesheet = $xslt->parse stylesheet($style);
transform the source file
my $results = $stylesheet->transform($doc);
print the result to STDOUT
print $stylesheet->output string($results);
Here is how the program works:
The necessary modules (XML::LibXML and XML::LibXSLT) are "included" in the script.
An XSLT stylesheet file name and an XML data file name are read from the command line.