In the event that mirod has not managed to convert you to XML::Twig :-) then here's one code snippet to do what (I think) you want:
#!/usr/bin/perl use strict; use warnings; use XML::Simple; my $file = './Test.xml'; my $head = $ARGV[0] || 'Unknown'; my $map = XMLin($file, forcearray => ['header', 'act'], keyattr => { h +eader => 'name'}); my $header = $map->{header}->{$head}; if($header) { foreach my $act ( @{$header->{act}} ) { print "act: $act\n"; } } else { print "No match for '$head'\n"; }
Alternatively, you could iterate through the <header> items by using the keyattr option to turn off array folding:
my $map = XMLin($file, forcearray => ['header', 'act'], keyattr => {}) +; my $headers = $map->{header}; foreach my $header (@$headers) { if($header->{name} eq $head) { foreach my $act ( @{$header->{act}} ) { print "act: $act\n"; } } }
By the way, your original code included this logic:
unless ($config = $xs1->XMLin($file, forcearray => 1)) { print "Could NOT read $file IN:$!\n"; exit(); }
That won't actually work, since if XML::Simple can't parse the XML it will call 'die' rather than returning a false value. If you want to trap errors, you'd need to wrap the call to XMLin() in an eval block and check $@ afterwards.
In reply to Re: XML::Simple parsing
by grantm
in thread XML::Simple parsing
by AcidHawk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |