Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Check if XML element exists

by johnfl68 (Scribe)
on Mar 26, 2013 at 00:58 UTC ( [id://1025422]=perlquestion: print w/replies, xml ) Need Help??

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

Hello:

I thought I had this figured out once before, but now it's not coming to me (or at least not quit right). I always seem to have troubles with the whole hash/array thing as my brain always seems to interpret it differently than it is.

I have a XML file, some of the data entries have 'codeshares' elements, and some do not. Some have only 1 and others may have 2 or 3.

I am using XML::Simple because is works for 98% of what I need.

I have tried using the following in hopes to get a number response back based on the number of codeshares entries:

  my $codeshares = scalar @{$database->{'flightStatuses'}->{'flightStatus'}->[$loop]->{'codeshares'}->{'codeshare'}};

And a XML Sample:

<flightStatuses> <flightStatus> <flightId>292085149</flightId> <carrierFsCode>MQ</carrierFsCode> <flightNumber>4070</flightNumber> <codeshares> <codeshare> <fsCode>AA</fsCode> <flightNumber>4070</flightNumber> <relationship>X</relationship> </codeshare> <codeshare> <fsCode>BA</fsCode> <flightNumber>4841</flightNumber> <relationship>Z</relationship> </codeshare> </codeshares> </flightStatus> </flightStatuses>

But if it is less than 2 codeshares, I get "Not an ARRAY reference at..." back. If I have 2 or more codeshares it seems to work fine.

Anyone know what I might possibly be missing, or is there another way to find out (in this case) how may codeshares there are, so I can read them? Everything else I have so far works fine.

Thanks as always!

John

Replies are listed 'Best First'.
Re: Check if XML element exists
by choroba (Cardinal) on Mar 26, 2013 at 01:16 UTC
    If you want an array always, use the ForceArray option.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Thanks:

      I added:

      ForceArray => ['codeshare']

      to the XMLin, and that seems to take care of things.

      Thanks again!

      John

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1025422]
Approved by sundialsvc4
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2024-04-23 08:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found