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

Having trouble accessing the elements of the associative arrary XML::Simple creates
my code:

$xml = new XML::Simple;
$data = $xml->XMLin("data.xml");
print $data->{employee}->[0]->{name};

the last line above is what doesn't work.
error: Not an ARRAY reference at file.pl Line 3 XML File:
<?xml version='1.0'?> <employees> <employee> <name>John Doe</name> <age>43</age> <sex>M</sex> <department>Operations</department> </employee> <employee> <name>Jane Doe</name> <age>31</age> <sex>F</sex> <department>Accounts</department> </employee> </employees>
So, trying to print out one of the names... can't get the syntax right. If I go: print $data->{employee}; I get a hash reference... does that mean I have to put it into a hash first?

Replies are listed 'Best First'.
Re: XML::Simple - multi level
by runrig (Abbot) on Dec 07, 2007 at 20:29 UTC
    You want to check out the ForceArray and KeyAttr options. specifically:
    my $xml = XML::Simple->new( ForceArray => [ 'employee' ], KeyAttr => [ +] ); my $data = $xml->XMLin( "data.xml" ); use Data::Dumper qw(Dumper); print Dumper $data;
    Update: Actually, you don't need the ForceArray in this instance, but it is one of the most used options in the module, and you would need it if, e.g., you might only have one employee, so my advice to check out those options still stands :-)
Re: XML::Simple - multi level
by olus (Curate) on Dec 07, 2007 at 21:18 UTC
    There is a note on the module documentation that says:
    Note 1: The default value for 'KeyAttr' is ['name', 'key', 'id']. If y +ou do not want folding on input or unfolding on output you must setti +ng this option to an empty list to disable the feature.
    If your element 'name' had a different name, things would have worked as you expected, but by default XML::Simple recognizes 'name' hence the need to setup the module with an empty 'KeyAttr' as runrig said.
      Set keyattr to and empty list and it's working now. Thanks guys. However, I suppose I don't really need this module for what i'm doing, but I'm glad I got it working. I'm just extracting one tag from an XML file. I can do that just as easily with a slurp and a regex.