Announce: Role-LibXSLT-Extender

Kip Hampton <[email protected]>
Newsgroups gmane.comp.lang.perl.moose,gmane.comp.lang.perl.xml
Message-ID <[email protected]>
Howdy!

I've just released the first version of Role::LibXSLT::Extender to CPAN.

What is it?

Role::LibXSLT::Extender is a simple Moose Role that instantiates an 
XML::LibXSLT processor and registers the subroutines and methods in the 
class that consumes that Role as extension functions that can be called 
from within your XSLT stylesheets.

Why the $#&% would I want this?

XSLT is great for recursively transforming nested XML documents but 
operating on the text in those documents can be time consuming and 
error-prone. Perl is great for all sort of things, but transforming 
nested XML documents programmatically is the source of much unnecessary 
pain and consternation. This module seeks to bridge the gap by letting 
you use XSLT for what it is best at while using the power of Perl for 
everything else.

Alright, but how do I use it?

Here's the SYNOPSIS:

# your extension class
package My::Special::XSLTProcessor
use Moose;
with 'MooseX::LibXSLT::Extender';

sub set_extension_namespace {
     return 'http:/fake.tld/my/app/namespace/v1'
}

sub special_text_munger {
     my $self = shift;
     my $text = shift;

     # magic happens here

     return $text;
}

-------------------
# in your XSLT stylesheet

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:myapp="http:/fake.tld/my/app/namespace/v1">

<xsl:template match="/some/xpath">
     <!-- pass the current text node to special_text_munger()
          in your extension class. -->
     <foo><xsl:value-of select="myapp:special_text_munger(.)"/></foo>
</xsl:template>

-------------------
# in your application or script

my $extended = My::Special::XSLTProcessor->new();

# load the XML and XSLT files
my $style_dom = XML::LibXML->load_xml( location=> $xsl_file );
my $input_dom = XML::LibXML->load_xml( location=> $xml_file );
my $stylesheet = $extended->parse_stylesheet($style_dom);

# your custom extensions are called here
my $transformed_dom = $stylesheet->transform( $input_dom );

# dump the result to STDOUT
print $stylesheet->output_as_bytes($transformed_dom);

But wait, there's more!

Unlike the vanilla XML::LibXSLT extension mechanism, functions 
registered via MooseX::LibXSLT::Extender are *methods* not just 
subroutines. Each function gets an instance of the class (you know, 
$self) so you have full access to all the other attributes, methods, 
etc. in that class without having to resort to global variables and so on.

As usual, comments, suggestions, flames, and patches are all welcome.

Cheers,
-kip
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.