X hits on this document

379 views

0 shares

1 downloads

0 comments

101 / 142

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:

#!/usr/bin/perl

  • #

    require the necessary modules

use strict; use XML::LibXML; use XML::LibXSLT;

my $xslt_fil

e = $ARGV[0];

my $xml_file

= $ARGV[1];

  • #

    get input

  • #

    initialize

my $parser my $xslt

= XML::LibXML->new; = XML::LibXSLT->new;

# parse the

input files

my $style

=

$parser->parse

my $doc

=

$parser->parse

_ _

file($xslt_file); file($xml_file);

  • #

    validate stylesheet

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);

_

  • #

    done

exit;

Here is how the program works:

  • 1.

    The necessary modules (XML::LibXML and XML::LibXSLT) are "included" in the script.

  • 2.

    An XSLT stylesheet file name and an XML data file name are read from the command line.

93

Document info
Document views379
Page views385
Page last viewedSat Dec 03 18:02:24 UTC 2016
Pages142
Paragraphs3126
Words34660

Comments