在 Perl 中创建 XML 文件 [英] XML file creation in Perl
问题描述
我的输入文件是
TBLA COLA A B
TBLA COLB D E
TBLB COLX M N
TBLB COLD A B
TBLC COLD A B
要以xml格式创建的输出为
The output to be created in xml format as
<Data>
<TBLA>
<COLA>
<oldvalue>A</oldvalue>
<newvalue>B</newvalue>
</COLA>
<COLB>
<oldvalue>D</oldvalue>
<newvalue>E</newvalue>
</COLB>
</TBLA>
<TBLB>
<COLX>
<oldvalue>M</oldvalue>
<newvalue>N</newvalue>
</COLX>
<COLD>
<oldvalue>A</oldvalue>
<newvalue>B</newvalue>
</COLD>
</TBLB>
<TBLC>
<COLD>
<oldvalue>A</oldvalue>
<newvalue>B</newvalue>
</COLD>
</TBLC>
</Data>
任何人都可以建议什么是最好的方法来做到这一点.我应该先将此文本文件转换为哈希值,然后再尝试使用 pltoxml()
.这有意义吗.XML::Simple
或 XML::Writer
是否就足够了.
Can anyone suggest what would be the best way to do this. Should i convert this text file to hash of hashes first and then try using pltoxml()
. does this make sense. Can XML::Simple
or XML::Writer
suffice this.
这是我第一次处理 xml,不确定哪种方法可以有效地帮助我的解决方案.
一个小例子wrt我的要求将不胜感激.
This is the first time I am working on xml and not sure which approach will help efficicently my solution.
A small example wrt to my req would be appreciated.
*输入文件将始终按第一个字段排序
*Input file will always be sorted on first field
推荐答案
鉴于非常简单的数据结构,使用整个 XML 编写器似乎有点不必要.但是,我将假定表名和列名是有效的 XML 标记名.
Given the very simple data structure, It seems a bit unneccessary to use a whole XML writer. However, I'll assume that that the table and column names are valid XML tag names.
这是一个简单的脚本,它读取数据而不将其存储在中间数据结构中.它适用于 perl5 v10 和更好的版本.
Here is a simple script that reads through the data without storing it in an intermediary data structure. It works with perl5 v10 and better.
use strict; use warnings; use feature 'say';
my $last_table;
say '<Data>';
while(<>) {
chomp;
my ($table, $col, $old, $new) = split /\t/;
s/&/&/g, s/</</g for $old, $new;
# I'll assume $table and $col have sane names
if (not defined $last_table) {
say " <$table>";
} elsif ($last_table ne $table) {
say " </$last_table>";
say " <$table>";
}
$last_table = $table;
say " <$col>";
say " <oldvalue>$old</oldvalue>";
say " <newvalue>$new</newvalue>";
say " </$col>";
}
say " </$last_table> if defined $last_table;
say '</Data>';
这篇关于在 Perl 中创建 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!