输入文件:SN.xml
<?xml version='1.0'?>
<root>
<category cname='Cname1' id='c1'>
<subcat key='3' sname='Subname1' sid='sid1'>
<prod key='1' pname='Productname'>value1</prod>
</subcat>
<subcat key='4' sname='Subname2' sid='sid1'>
<prod key='1' pname='Productname1'>value2</prod>
<prod key='2' pname='Productname2'>value3</prod>
</subcat>
</category>
</root>
我必须得到如下的输出
Subname1 -> Productname
Subname2 -> Productname1
Subname2 -> Productname2
我使用哈希
试过下面的代码use strict;
use warnings;
use XML::Simple;
my $last;
my $sub_catname;
my $filename='SN.xml';
my $xs = XML::Simple->new();
my $config = $xs->XMLin($filename);
my $s_category = $config->{'category'}{'subcat'};
foreach my $key (sort (keys %{$s_category})){
my $subcat_val=$s_category->{$key}{'sname'};
$last=$key;
$sub_catname=$subcat_val;
}
my $prod = $s_category->{$last}{'prod'};
foreach my $key (sort {$a<=>$b} keys %{$prod}){
my $res_prod = $prod->{$key}{'pname'};
print "$sub_catname -> $res_prod\n";
}
我得到空输出。 我试过data :: dumper工作正常。我无法使用循环打印输出。 在此先感谢。
答案 0 :(得分:0)
使用Data::Dumper可视化复杂的数据结构。这为您提供了所需的输出,并显示了结构:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use XML::Simple;
my $filename = 'SN.xml';
my $xs = 'XML::Simple'->new( ForceArray => ['prod'] );
my $config = $xs->XMLin($filename);
print Dumper $config;
for my $s_category (keys %{ $config->{category}{subcat} }) {
for my $prod (keys %{ $config->{category}{subcat}{$s_category}{prod} }) {
print $config->{category}{subcat}{$s_category}{sname}, ' -> ',
$config->{category}{subcat}{$s_category}{prod}{$prod}{pname}, "\n";
}
}
为了进行比较,您可以使用XML::XSH2({3}}的包装器获得相同的结果:
open SN.xml ;
for /root/category/subcat {
my $sname = @sname ;
for prod/@pname echo $sname -> (.) ;
}
答案 1 :(得分:0)
use strict;
use warnings;
use XML::Simple;
my $last;
my $filename='SN.xml';
my $xs = XML::Simple->new(ForceArray => [qw( prod )]);
my $config = $xs->XMLin($filename);
my $s_category = $config->{'category'}{'subcat'};
foreach my $key (sort (keys %{$s_category})){
my $subcat_val=$s_category->{$key}{'sname'};
$last=$key;
}
my $prod = $s_category->{$last}{'prod'};
foreach my $key (sort {$a<=>$b} keys %{$prod}){
my $res_prod = $prod->{$key}{'pname'};
print "$last -> $res_prod\n";
}