如何使用像这样的Perl数组
@categories = ( ["Technology", "Gadgets"], ["TV & Film"] );
并生成此XML代码段?
<itunes:category text="Technology">
<itunes:category text="Gadgets"/>
</itunes:category>
<itunes:category text="TV & Film"/>
如果有更简单的方法来获得相同的输出,我可以更改数组。
答案 0 :(得分:4)
我实际上认为XML :: Simple是最容易使用的xml模块之一,具体取决于您的需求。
您在上面引用的代码段实际上并不是有效的xml没有根标记。您要生成片段还是完整有效的xml文档?
XML :: Generator是另一个好的。这些都不会产生你在那里的片段,因为它们将包含一个根标签。
考虑到您在下面的评论中提出问题的动机,您可能需要查看:Mac::Itunes::Library::XML
作为一般推论:大多数时候处理perl search.cpan.org会找到你需要的东西,http://cpanratings.perl.org/会告诉你如果有一个社区收到的东西是多么好很多选择。
答案 1 :(得分:2)
我不知道为什么Inshalla的答案被低估了,因为XML::Generator&amp; XML::Writer都是写出XML的好模块。
使用你评论过的Whats on iTunes? spec,这就是使用XML :: Generator看起来的样子:
use strict;
use warnings;
use XML::Generator;
my $x = XML::Generator->new( pretty => 2, conformance => 'strict' );
my $itunes_ns = [ 'itunes' => 'http://www.itunes.com/dtds/podcast-1.0.dtd' ];
say $x->xmldecl( encoding => 'UTF-8' );
say $x->rss(
$x->channel(
$x->title('All about Everything'),
$x->category( $itunes_ns, { text => 'Technology' },
$x->category( $itunes_ns, { text => 'Gadgets' } ),
),
$x->category( $itunes_ns, { text => 'TV & Film' } ),
),
);
这会产生:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<channel>
<title>All about Everything</title>
<itunes:category text="Technology">
<itunes:category text="Gadgets" />
</itunes:category>
<itunes:category text="TV & Film" />
</channel>
</rss>
要回答“将perl数组转换为XML”,这里有一个例子:
use strict;
use warnings;
use XML::Generator;
my $x = XML::Generator->new( pretty => 2, conformance => 'strict' );
my $itunes_ns = [ 'itunes' => 'http://www.itunes.com/dtds/podcast-1.0.dtd' ];
my @categories = ( { "Technology" => [ "Gadgets", 'Gizmo' ] }, "TV & Film" );
say $x->xmldecl( encoding => 'UTF-8' );
say $x->rss(
$x->channel(
$x->title('All about Everything'),
map { recurse( $_ ) } @categories,
),
);
sub recurse {
my $item = shift;
return $x->category( $itunes_ns, { text => $item } )
unless ref $item eq 'HASH';
my ($k, $v) = each %$item;
return $x->category( $itunes_ns,
{ text => $k },
map { recurse ( $_ ) } @$v );
}
看看之前的SO问题something a bit similar
答案 2 :(得分:1)
有关使用perl生成XML的一般方法,请查看XML::Generator或XML::Writer。
答案 3 :(得分:1)
对于初学者,我肯定会改变阵列。 (数据和您想要的XML片段之间没有明显的映射。)
类似下面的POO表示?
my $categories = {
"Technology" => {
"Gadgets" => undef
},
"TV & Film" => undef
};