drodinthe559 has asked for the wisdom of the Perl Monks concerning the following question:

Hey Gurus: I'm try to pull data from an XML file that has multiple levels. There are multiple batches that have an index hash assigned to them. Within those batches there are items that have there own index hashes assigned to them (e.g. [0] in the loop). I've attached a few screen shots in that it will be easier to see the data structure.
#!/usr/bin/perl -w use strict; use warnings; use File::Glob; use XML::Simple; use Data::Dumper; my @files = glob("//Server/Share/*.xml"); my $xml = XML::Simple->new(KeyAttr=>[]); #, ForceArray=>1); foreach my $x (@files) { my $data = $xml->XMLin($x); foreach my $key (@{$data->{Jobs}->{Job}->{Blocks}->{Block}->{Batch +es}->{Batch}->[0]->{Items}->{Item}}) { print $key->{CorporateName} . "\n"; print $key->{Amount} . "\n"; } }

Replies are listed 'Best First'.
Re: XML::Simple Multi Level Array
by GrandFather (Saint) on Feb 11, 2010 at 04:59 UTC

    Not addressing your issue, but

    $data->{Jobs}->{Job}->{Blocks}->{Block}->[0]

    is more succinctly written:

    $data->{Jobs}{Job}{Blocks}{Block}[0]

    True laziness is hard work
Re: XML::Simple Multi Level Array
by desemondo (Hermit) on Feb 11, 2010 at 02:06 UTC
    I've attached a few screen shots in that it will be easier to see the data structure.
    I'm not sure what you meant by that, but it doesn't appear to have worked.

    Also, what exactly are you having difficulty with? How do I post a question effectively?
      How do I loop through the hash in the {Batch} index? You'll notice I have a zero.
        # This looks wrong, but it's what you gave us my $batches = $data->{Jobs}{Job}{Blocks}{Block}{Batches}{Batch}; for my $batch (@$batches) { # This looks also wrong my $item = $batch->{Items}{Item}; print $item->{CorporateName} . "\n"; print $item->{Amount} . "\n"; }
        I would have expected something more like
        my $jobs =$data->{Jobs}{Job}; for my $job (@$jobs) { my $blocks = $job->{Blocks}{Block}; for my $block (@$blocks) { my $batches = $job->{Batches}{Batch}; for my $batch (@$batches) { my $items = $batch->{Items}{Item}; for my $item (@$items) { print $item->{CorporateName} . "\n"; print $item->{Amount} . "\n"; } } } }

        By the way , the following would simplify your tree:

        GroupTags => { Jobs => 'Job', Blocks => 'Block', Batches => 'Batch', },