I worked through your XML example (which was malformed... I hope you made mistakes while re-typing, or else you really need to fix the source XML file). Your problem seems to be that XML::Simple returns different types of data depending on what's in the XML file. If it finds only one element, it puts a scalar in the returned hash. If it finds more than one, it returns a reference to an array of data.

Not having used this module myself, I thought this was difficult behavior, but after RTFM, it turns out there is an option (clearly marked "important") to force certain elements to always be represented as arrays, even if there is only one. I turned that on and then got the code to run on a modified version of your XML block. I tried to mark the important parts in the code below:
#!/usr/bin/perl # use module use strict; use warnings; use XML::Simple; use Data::Dumper; # create object my $xml = new XML::Simple (KeyAttr=>[], ForceArray => ['function']); # IMPORTANT ^^^^^^^^^^ # read XML file my $data = $xml->XMLin("hosts.xml"); my $e = $data->{'host'}; print "Name: ", $e->{name}, "\n"; # IMPORTANT: Use a loop to process all the possible # functions, instead of just one. foreach my $fct ( @{$e->{'function'}} ){ print "Function: ", $fct, "\n"; }
<allHosts> <host name="jimmy"> <function>web</function> <function>dns</function> <location>miami</location> </host> </allHosts>
Please use strict and warnings int he future, as it would have alerted you to the problems in your code instead of silently giving you no output.

In reply to Re: XML parsing by crashtest
in thread XML parsing by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.