繁体   English   中英

如何在Perl中创建XML模板?

[英]How do I create an XML template in Perl?

我需要创建的XML文件就像

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

我不想使用多个print来创建所需的XML文件,我期望的是有一个模板,它定义了XML的结构和格式。

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

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

您可以使用Template::Toolkit来执行此操作

cpan有几个你可以使用的XML模块。

我的建议是你从XML::SimpleXML::API

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM