如何在 Perl 中创建 XML 模板? [英] How do I create an XML template in Perl?

查看:46
本文介绍了如何在 Perl 中创建 XML 模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建的 XML 文件就像

The XML file I need to create is like

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

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

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.

然后在创建 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.

推荐答案

use HTML::模板.

#!/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>

这篇关于如何在 Perl 中创建 XML 模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆