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

I am using XML::Simple to parse a pretty non-complex xml file that deals with nodes on a network.

<network> <node name="edge1"> <community>something</community> <loopback></loopback> </node> <node name="edge2"> <community>anotherthing</community> <loopback></loopback> <loopback></loopback> </node> </network>

Now, I see how to grab the value of a field that has multiple choices. Such as edge2's loopbacks.

my $i =XMLin("xmlfile"); print "$i->{node}->{edge2}->{loopback}->[1]\n";
I have a decent idea of how to loop over all of the loopbacks for a given node, however how do I loop over all of the given nodes? Trying something like:

print "$i->{node}->[1]\n";
gives me an error saying that there is no reference to a hash. I can understand this error, but I'm not sure how to get past it to print out a list of all the known "nodes" in my xml file. My ultimate goal is to pass over the list of nodes and act upon then using the information held nested beneath them in the same xml file.

thanks -c

Replies are listed 'Best First'.
Re: Using XML::Simple with nested arrays
by DamnDirtyApe (Curate) on Jul 05, 2002 at 00:21 UTC

    If you use Data::Dumper along with XML::Simple (the dynamic duo?) you can see that, using forcearray => 1 with XML::Simple, your XML becomes this:

    $VAR1 = { 'node' => { 'edge2' => { 'community' => [ 'anotherthing' ], 'loopback' => [ '', '' ] }, 'edge1' => { 'community' => [ 'something' ], 'loopback' => [ '' ] } } };

    So, I believe you want something like this:

    #! /usr/bin/perl use strict ; use warnings ; use XML::Simple ; #use Data::Dumper ; my $xml = <<'EOD' ; <network> <node name="edge1"> <community>something</community> <loopback></loopback> </node> <node name="edge2"> <community>anotherthing</community> <loopback></loopback> <loopback></loopback> </node> </network> EOD my $data = XMLin( $xml, forcearray => 1 ) ; #print Dumper( $data ) ; foreach my $key ( keys %{$data->{'node'}} ) { foreach my $loopback ( @{$data->{'node'}{$key}{'loopback'}} ) { print "key = $key; loopback = $loopback\n" ; } }


    key = edge2; loopback = key = edge2; loopback = key = edge1; loopback =

    D a m n D i r t y A p e
    Home Node | Email
Re: Using XML::Simple with nested arrays
by BrowserUk (Patriarch) on Jul 05, 2002 at 03:38 UTC

    If, as I did, you find the output of DATA::Dumper less than optimal for working out your refs to XML::Simple structures, you might find this useful.