当你写:
@{ $booklist->{detail} }
...您是说 $booklist->{detail} 返回一个数组引用,并且您希望 perl 将其取消引用到一个数组中,即“@”。
不要<name>
用作标签。XML::Simple 会奇怪地解析它。这是一个例子:
1)
<?xml version='1.0' encoding='iso-8859-1'?>
<booklist>
<book>
<bname>book1</bname>
</book>
<book>
<bname>book2</bname>
</book>
</booklist>
use strict;
use warnings;
use 5.016;
use XML::Simple;
use Data::Dumper;
my $booklist = XMLin('xml.xml');
print Dumper($booklist);
--output:--
$VAR1 = {
'book' => [
{
'bname' => 'book1'
},
{
'bname' => 'book2'
}
]
};
2) 现在看看使用<name>
标签时会发生什么:
<?xml version='1.0' encoding='iso-8859-1'?>
<booklist>
<book>
<name>book1</bname>
</book>
<book>
<name>book2</bname>
</book>
</booklist>
--output:--
$VAR1 = {
'book' => {
'book2' => {},
'book1' => {}
}
};
所以用你原来的例子:
<?xml version='1.0' encoding='iso-8859-1'?>
<booklist>
<book>
<detail label='label1' status='active' type='none'>
<bname>book1</bname>
</detail>
<detail label='label2' status='active' type='none'>
<bname>book2</bname>
</detail>
</book>
</booklist>
--output:--
$VAR1 = {
'book' => {
'detail' => [
{
'bname' => 'book1',
'status' => 'active',
'label' => 'label1',
'type' => 'none'
},
{
'bname' => 'book2',
'status' => 'active',
'label' => 'label2',
'type' => 'none'
}
]
}
};
要获取所有 bname 标签,您可以这样做:
use strict;
use warnings;
use 5.016;
use XML::Simple;
use Data::Dumper;
my $booklist = XMLin('xml.xml');
my $aref = $booklist->{book}{detail};
for my $href (@$aref) {
say $href->{bname};
}
--output:--
book1
book2