[Perl Other] perl中给hash转换成xml输出
转载本站文章请注明,转载自:扶凯[http://www.php-oa.com]
本文链接: http://www.php-oa.com/2009/08/13/outputting-a-hash-as-xml.html
因为使用需要,做一个xml的接口.需要给hash转成xml,google了一下,发现了如下极品…得好好学习
#!/usr/bin/perl
use strict;
use XML::Twig;
my %all = (
Video => {
Width => '960pixels',
CodecID => 'H264',
Height => '540pixels',
},
Audio => {
FormatInfo => 'AudioCoding3',
Streamsize => '120MiB',
Samplingrate => '48.0KHz',
},
General => {
Format => 'AVI',
Duration => '43mn45s',
Filesize => '436MiB',
},
);
my $twig = XML::Twig->new(pretty_print => 'indented');
my $elt = create_element(info => \%all);
$twig->set_root($elt);
$twig->print();
sub create_element{
my $gi = shift;
my $data = shift;
my $t = XML::Twig::Elt->new($gi);
if (ref $data){
while (my ($k,$v) = each(%$data)){
create_element($k, $v)->paste(last_child => $t);
}
}else{
$t->set_text($data);
}
$t;
}
测试,上面有个all的hash的hash.转换后如下输出
# perl test2.pl
<info>
<Video>
<Height>540pixels</Height>
<Width>960pixels</Width>
<CodecID>H264</CodecID>
</Video>
<General>
<Filesize>436MiB</Filesize>
<Duration>43mn45s</Duration>
<Format>AVI</Format>
</General>
<Audio>
<Samplingrate>48.0KHz</Samplingrate>
<FormatInfo>AudioCoding3</FormatInfo>
<Streamsize>120MiB</Streamsize>
</Audio>
</info>
要是想输出到一个文件之类,可以用下面的方法
-
#!/usr/bin/perl
-
-
use strict;
-
use XML::Writer;
-
-
print "Content-type: text/xml\n\n";
-
-
my $xml = new XML::Writer();
-
-
$xml->startTag("root");
-
$xml->startTag("messages");
-
$xml->dataElement(msg1=> "Hello World");
-
$xml->dataElement(msg2=> "Goodbye World");
-
$xml->endTag();
-
$xml->endTag();
-
$xml->endTag();
-
$xml->end();
参考:
www.perlmonks.org/
tech.idv2.com/2007/09/14/generate-xml-with-xml-dom/



















Как данное действие можно осуществить и с какими комиссиями?
———————————————————
Стоимость Оптимизация сайта, Продвижение.
SEO-аудит Подбор сайта, Раскрутка.
太专业了 看不懂 纯支持!