Perl XML parsing using foreach

robocop100
robocop100 used Ask the Experts™
on
I have XML which may contain an unknown number of <A> and <B> elements:

<?xml version="1.0" encoding="UTF-8" ?>
<Messages>
   <A>
       <Message>
         <Field1>
         <Field2>
         <Field3>
       </Message>
   </A>
   <B>
       <Message>
         <Field1>
         <Field2>
         <Field3>
       </Message>
   </B>
   <B>
       <Message>
         <Field1>
         <Field2>
         <Field3>
       </Message>
   </B>
   <B>
       <Message>
         <Field1>
         <Field2>
         <Field3>
       </Message>
   </B>
</Messages>

I read in the data like this:
my $data = XMLin($content);

I can parse all the <B> elements like this:

foreach $b_msg (@{$data->{B}->{Message}})

but the same does not work for <A> elements:

foreach $b_msg (@{$data->{A}->{Message}})

I don't understand why I can loop through all the <B> elements but the foreach for the <A> elements is never entered.

Please explain. Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
In the post above I missed out the closing tags for Field1, Field2, and Field3. Please assume the XML is well-formed
Change the XMLin to:

my $data = XMLin($content, ForceArray => [qw(A B)]);

Author

Commented:
Seems to work now for traversing the <A> elements but not the <B> elements

Author

Commented:
I made a mistake - yes it is working using the info provided by wilcoxon above. Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial