Solution :-
Here are some basic use of forcearray option in XMLin subroutine of XML::Simple module.
Here are 3 examples :-
use XML::Simple;
my $xml = qq~<user>
<fname>Lalit</fname>
<pnr>WERTED</pnr>
<pnr>TREFDS</pnr>
<passenger>BCDE</passenger>
</user>~;
Example 1 :-
my $data = XMLin($xml); # Without forcearray
By default XML::Simple return elements as scalar - unless no duplicate node found.
In duplicate node case it return arrayref.
In this example we have to check the elements is arrayref or not.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $value(ref($element) =~ /ARRAY/ ? @$element : $element) {
print $keys."=>".$value."\n";
}
}
Example 2 :-
my $data = XMLin($xml, forcearray => 1);
In this example we do not have to check the elements is arrayref or not, because we are setting the forcearrayref 1. It always represent child elements as arrayrefs - even if there's only one.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $value(@$element) {
print $keys."=>".$value."\n";
}
}
Example 3 :-
my $data = XMLin($xml, forcearray => ['pnr']);
In this example only those element will be arrayref where key is pnr, so we can access the element by using key name also.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $values ($keys =~ /pnr/ ? @$element : $element) {
print $keys."=>".$values."\n\n";
}
}
Here are 3 examples :-
use XML::Simple;
my $xml = qq~<user>
<fname>Lalit</fname>
<pnr>WERTED</pnr>
<pnr>TREFDS</pnr>
<passenger>BCDE</passenger>
</user>~;
Example 1 :-
my $data = XMLin($xml); # Without forcearray
By default XML::Simple return elements as scalar - unless no duplicate node found.
In duplicate node case it return arrayref.
In this example we have to check the elements is arrayref or not.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $value(ref($element) =~ /ARRAY/ ? @$element : $element) {
print $keys."=>".$value."\n";
}
}
Example 2 :-
my $data = XMLin($xml, forcearray => 1);
In this example we do not have to check the elements is arrayref or not, because we are setting the forcearrayref 1. It always represent child elements as arrayrefs - even if there's only one.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $value(@$element) {
print $keys."=>".$value."\n";
}
}
Example 3 :-
my $data = XMLin($xml, forcearray => ['pnr']);
In this example only those element will be arrayref where key is pnr, so we can access the element by using key name also.
foreach my $keys (keys %$data) {
my $element = $data->{$keys};
foreach my $values ($keys =~ /pnr/ ? @$element : $element) {
print $keys."=>".$values."\n\n";
}
}