从文件生成类似代码的XML

时间:2013-01-27 16:26:07

标签: xml perl csv

目标已定为我,但我不知道如何到达那里。提前道歉。

使用Perl - 我将收到一个字符分隔文件(我可以指定其结构),我需要将其转换为XML 之类的文件

<MyConfig>
   Active = yes
   Refresh = 10 min
 <Includes>
 <Include_Rule_1>
 Active = yes
 Match = /Foo [Bb]ar/
 </Include_Rule_1>
 <Include_Rule_2>
 Active = yes
 Match = /Baz.*/
<Include_Rule_2>
</Include>
<Exclude>
<Exclude_Rule_1>
Exclude = /Bim Bam/
</Exclude_Rule_1>
 </Exclude>
</MyConfig>

简而言之,它将是XML ,如(单个值不被尖括号包围),其中3个部分是常量但其深度始终是未知的。

我可以使用CPAN库但不喜欢这个,因为这个脚本需要在我无法访问或控制的单个服务器上运行。

有什么想法吗?入门指针?提示或技巧?

对不起,我在这里迷路了。

2 个答案:

答案 0 :(得分:0)

您可以在此初始化示例中使用Template::Toolkit模块(您需要首先解析输入文件以提供HASH):

#!/usr/bin/env perl

use strict; use warnings;
use Template;
my $tt = Template->new;
my $input = {
    MyConfig_Active => "yes",
    MyConfig_refresh => "10 min",
    MyConfig_Include_Rule_1_Active => "yes",
    MyConfig_Include_Rule_1_Match => "/Foo [Bb]ar/"
};
$tt->process('template.tpl', $input)
    || die $tt->error;

template.tpl档案:

<MyConfig>
   Active = [% MyConfig_Active %]
   Refresh =  [% MyConfig_refresh %]
 <Includes>
 <Include_Rule_1>
 Active = [% MyConfig_Include_Rule_1_Active %]
 Match = "[% MyConfig_Include_Rule_1_Match %]"
 </Include_Rule_1>
(...)
</MyConfig>

示例输出:

<MyConfig>
   Active = yes
   Refresh =  10 min
 <Includes>
 <Include_Rule_1>
 Active = yes
 Match = "/Foo [Bb]ar/"
 </Include_Rule_1>
(...)
</MyConfig>

请参阅http://template-toolkit.org/docs/tutorial/Datafile.html

答案 1 :(得分:0)

一种选择是使用Config::General从您从解析后的字符分隔文件的结果中填充的哈希生成此类文件。使用Config :: General可以轻松读回此文件以重新填充哈希:

use strict;
use warnings;
use Config::General;

my %config = (
    Active   => 'yes',
    Refresh  => '10 min',
    Includes => {
        Include_Rule_1 => {
            Active => 'yes',
            Match  => '/Foo [Bb]ar/'
        },
        Include_Rule_2 => {
            Active => 'yes',
            Match  => '/Baz.*/'
        }
    },
    Excludes => { 
        Exclude_Rule_1 => { 
            Exclude => '/Bim Bam/'
        }
    }

);

my $conf = new Config::General();

# Save structure to file
$conf->save_file('myConfig.conf', \%config);

myConfig.conf的内容:

<Excludes Exclude_Rule_1>
    Exclude   /Bim Bam/
</Excludes>
Refresh   10 min
<Includes>
    <Include_Rule_1>
        Match   /Foo [Bb]ar/
        Active   yes
    </Include_Rule_1>
    <Include_Rule_2>
        Match   /Baz.*/
        Active   yes
    </Include_Rule_2>
</Includes>
Active   yes