Substitute values into a template
use XML::Grove::Subst; # Using subst method on XML::Grove::Document or XML::Grove::Element: $new_grove = $source_grove->subst( ARGS ); $new_grove = $source_grove->subst_hash( ARG ); # Using an XML::Grove::Subst instance: $subster = XML::Grove::Subst->new(); $new_grove = $subster->subst( $source_grove, ARGS ); $new_grove = $subster->subst_hash( $source_grove, ARG );
\*(C`XML::Grove::Subst\*(C' implements \s-1XML\s0 templates. \*(C`XML::Grove::Subst\*(C' traverses through a source grove replacing all elements with names `\*(C`SUB:XXX\*(C'' or `\*(C`SUB:key\*(C'' with their corresponding values from \s-1ARGS\s0 (a list) or \s-1ARG\s0 (a hash), repsectively.
Search for `\*(C`SUB:XXX\*(C'' elements, where \s-1XXX\s0 is an array index, and replace the element with the value from \s-1ARGS\s0, a list of values. The return value is a new grove with the substitutions applied. Search for `\*(C`SUB:key\*(C'' elements and replace the element with the value from \s-1ARG\s0, a hash of values. The hash key is taken from the `\*(C`key\*(C'' attribute of the `\*(C`SUB:key\*(C'' element, for example, `\*(C`<SUB:key key='foo'>\*(C''. The return value is a new grove with the substitutions applied.
The following template, in a file `\*(C`template.xml\*(C'', could be used for a simple parts database conversion to \s-1HTML:\s0
<html> <head> <title><SUB:key key='Name'></title> </head> <body> <h1><SUB:key key='Name'></title> <p>Information for part number <SUB:key key='Number'>:</p> <SUB:key key='Description'> </body> </html>
To use this template you would first parse it and convert it to a grove, and then use `\*(C`subst_hash()\*(C'' every time you needed a new page:
use XML::Parser::PerlSAX; use XML::Grove; use XML::Grove::Builder; use XML::Grove::Subst; use XML::Grove::PerlSAX; use XML::Handler::XMLWriter;
# Load the template $b = XML::Grove::Builder->new(); $p = XML::Parser::PerlSAX->new( Handler = $b ); $source_grove = $p->parse( Source => { SystemId => 'template.xml' } );
# Apply the substitutions $new_grove = $source_grove->subst_hash( { Name => 'Acme DCX-2000 Filter', Number => 'N4728', Description => 'The Best' } );
# Write the new grove to standard output $w = XML::Handler::XMLWriter->new(); $wp = XML::Grove::PerlSAX->new( Handler => $w ); $wp->parse( Source => { Grove => $new_grove } );
Ken MacLeod, [email protected]
perl\|(1), XML::Grove\|(3)
Extensible Markup Language (\s-1XML\s0) <http://www.w3c.org/XML>