SVG, Unicode, and XSLT - Part 3 of Chapter 7 from Perl Graphics Programming (5/5)
[previous] |
Perl Graphics Programming, Chapter 7: Creating SVG with Perl
Example 7-4 defines five templates, one for matching each of the XML element types in the input document. When a <slide> element is encountered, the first template is matched, and the following actions occur:
- An SVG header is added to the output XML.
- A
<text>element for the title is added. The@titlevariable matches thetitleattribute of the<slide>element. - The image is added to the upper left corner. The image URL is extracted from the
<image>element with the{image}string. - The
<apply-templates>tag causes the remainder of the input document to be parsed, and the result is inserted here.
The remaining four templates perform the following actions:
- The template matching a
<textline>creates a new<tspan>element and applies the templates to its content. If the content does not match any of the templates, the text is passed directly to the output file. - Nothing is done for the template matching a
<bulletlist>, except that the templates are applied to each child of the<bulletlist>. - The template matching a
<bullet>creates a new<tspan>element and inserts a Unicode bullet before its text content. - Any image elements that appear in the document are discarded. The first template (matching the
<slide>element) has already extracted the image URL by this point.
Once we have created an XSLT script, we need to apply it to the input XML. For this you can use one of several freely available XSLT processors, many of which have Perl interfaces. Example 7-5 uses the Sablotron module, available on CPAN. Sablotron (see http://www.gingerall.com/ for more information) builds on the free Expat XML parser.
The Sablotron processor object maintains a set of internal "named buffers" that hold the result of a processed file. Example 7-5 is a simple wrapper that passes an XML file and template (XSLT) file to the Sablotron processor and prints the result in the internal arg:/result buffer.
Example 7-5: A simple XSLT processor
#!/usr/bin/perl
#
# Example 7-5. Using XSLT.
use strict;
use XML::Sablotron;
unless (defined($ARGV[0]) && defined $ARGV[1]) {
die "Usage: xsltprocessor.pl xml_input.xml xslt_input.xslt\n";
}
my $processor = new XML::Sablotron( );
$processor->runProcessor($ARGV[1],
$ARGV[0],
'arg:/result',
undef, undef);
print $processor->getResultArg("arg:/result");
The output is shown in Figure 7-4.

Figure 7-4. An SVG image generated from an XSLT transformation
[previous] |
Created: February 26, 2003
Revised: February 26, 2003
URL: http://webreference.com/programming/perl/chap7/3/5.html


