2009-08-20 87 views
2

我需要创建XML文件是像如何在Perl中创建XML模板?

<file> 
    <state>$state</state> 
    <timestamp>$time</timestamp> 
    <location>$location</location> 
      .... 
</file> 

我不想使用几种打印,创建所需的XML文件,我很期待是有一个模板,它定义了结构和XML的格式。

然后,当创建XML文件时,我只需要提供模板中变量的实际值,并将指定的模板写入新创建的文件一次,仅一次。

回答

8

使用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; 

输出:

<file> 
    <state>one</state> 
    <timestamp>two</timestamp> 
    <location>three</location> 
</file> 

<file> 
    <state>alpha</state> 
    <timestamp>beta</timestamp> 
    <location>gamma</location> 
</file> 
+0

答案正是我需要的。 – 2009-08-20 13:26:02

+1

嘿!好的HTML'模板! – innaM 2009-08-20 15:37:34