Avatar of robocop100
robocop100

asked on 

Perl XML parsing using foreach

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.
Perl

Avatar of undefined
Last Comment
robocop100
Avatar of robocop100
robocop100

ASKER

In the post above I missed out the closing tags for Field1, Field2, and Field3. Please assume the XML is well-formed
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of robocop100
robocop100

ASKER

Seems to work now for traversing the <A> elements but not the <B> elements
Avatar of robocop100
robocop100

ASKER

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

Perl is a high-level, general-purpose, interpreted, dynamic programming languages with over 25 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large-scale development projects. Perl gained widespread popularity as a Common Gateway Interface (CGI) scripting language, in part due to its regular expression and string parsing abilities. In addition to CGI, Perl is used for graphics programming, system administration, network programming, finance, bioinformatics, and other applications.

26K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo