我有下面的XML文件,我正试图解析它
<Books>
<book name="first" feed="contentfeed" mode="modes" />
<book name="first" feed="communityfeed" mode="modes" region="1"/>
<book name="second" feed="contentfeed" mode="" />
<book name="second" feed="communityfeed" mode="modes" />
<book name="second" feed="articlefeed" mode="modes" />
</Books>我与XML::Simple一起使用PERL5.8版本。下面是我写的代码
use XML::Simple;
my $xs = new XML::Simple( KeyAttr => { book => 'name' } , ForceArray => [ 'book','name' ] );
my $config = $xs->XMLin( <complete path to xml file> );下面是结果(使用Data::Dumper显示)
'book' => {
'first' => {
'feed' => 'communityfeed',
'mode' => 'modes',
'region' => '1'
},
'second' => {
'feed' => 'articlefeed',
'mode' => 'modes'
},
}相反,我希望输出的格式如下
'book' => {
'first' => {
'communityfeed' => { mode => 'modes', region => '1' },
'contentfeed' => { mode => 'modes' }
},
'second' => {
'communityfeed' => { mode => 'modes' },
'contentfeed' => { mode => '' },
'articlefeed' => { mode => 'modes' }
},
}备注
你以前遇到过这样的问题吗?如果是的话,又如何处理呢?
发布于 2016-06-06 23:02:54
XML::Simple是一个令人尴尬和令人沮丧的模块,我非常怀疑您能否说服它构建您所需的数据结构。几乎任何其他XML解析器都将向前迈进一步。
这里有一个使用XML::Twig的解决方案。您可以查询已解析的XML数据,并从中构建任何您喜欢的数据结构。
我只使用Data::Dump来显示结果数据
use strict;
use warnings 'all';
use XML::Twig;
my $config;
{
my $twig = XML::Twig->new;
$twig->parsefile('books.xml');
for my $book ( $twig->findnodes('/Books/book') ) {
my $atts = $book->atts;
my ( $name, $feed ) = delete @{$atts}{qw/ name feed /};
$config->{book}{$name}{$feed} = $atts;
}
}
use Data::Dump;
dd $config;输出
{
book => {
first => {
communityfeed => { mode => "modes", region => 1 },
contentfeed => { mode => "modes" },
},
second => {
articlefeed => { mode => "modes" },
communityfeed => { mode => "modes" },
contentfeed => { mode => "" },
},
},
}https://stackoverflow.com/questions/37667825
复制相似问题