How do I create an XML template in Perl?
The XML file I need to create is like
<file>
<state>$state</state>
<timestamp>$time</timestamp>
<location>$location</location>
....
</file>
I don't want to use multiple prints to create the required XML file, and I am expecting a template that defines the structure and format of the XML.
Then, when you create the XML file, I just need to provide the actual values ββfor the variables in the template, and write the specified template to the file I just created once, just once.
+2
source to share
3 answers
use HTML::Template
.
#!/usr/bin/perl
use strict;
use warnings;
use HTML::Template;
my $template_text = <<EO_TMPL;
<TMPL_LOOP FILES>
<file>
<state><TMPL_VAR STATE></state>
<timestamp><TMPL_VAR TIME></timestamp>
<location><TMPL_VAR LOCATION></location>
</file>
</TMPL_LOOP>
EO_TMPL
my $tmpl = HTML::Template->new( scalarref => \$template_text );
$tmpl->param(
FILES => [
{ state => 'one', time => 'two', location => 'three' },
{ state => 'alpha', time => 'beta', location => 'gamma' },
]);
print $tmpl->output;
Output:
<file>
<state>one</state>
<timestamp>two</timestamp>
<location>three</location>
</file>
<file>
<state>alpha</state>
<timestamp>beta</timestamp>
<location>gamma</location>
</file>
+8
source to share