views:

220

answers:

3

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 several print to create the needed XML file, what I'm expecting is to have a template, which defines both the structure and format of the XML.

Then when create the XML file, I just need to provide the actually values for the variables in the template and write the specified template to a newly created file once, only once.

+1  A: 

cpan has several XML modules you could use.

My suggestion is that you start with XML::Simple or XML::API

Nifle
+5  A: 

You can use Template::Toolkit to do that

ccheneson
+4  A: 

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>
Sinan Ünür
The answer is exactly what I need .
Haiyuan Zhang
Hey! good ol' html::template!
innaM