Re: Trouble accessing parsed XML variable
- From: "DJ Stunks" <DJStunks@xxxxxxxxx>
- Date: 7 Dec 2006 08:36:59 -0800
Robert McDonald wrote: (rearranged slightly by DJ Stunks)
Hello. I am trying to access data that is in XML format. Here is a test
program to illustrate the data I'm using and what I'm trying to do:
...
I would like to obtain a list of the colors and types.
...
my $mydata="
<food>
<fruit>
<color>red</color>
<type>apple</type>
</fruit>
<fruit>
<color>green</color>
<type>pear</type>
</fruit>
<fruit>
<color>yellow</color>
<type>banana</type>
</fruit>
</food>";
...
FYI, the print Dumper statement returns this:
'fruit' => [
{
'color' => 'red',
'type' => 'apple'
},
{
'color' => 'green',
'type' => 'pear'
},
{
'color' => 'yellow',
'type' => 'banana'
}
]
};
...
my $output= XMLin($mydata) ;
my $x=$output->{fruit};
foreach my $id (keys %$x) {
print "$id->{color} \n";
}
$x above isn't a hash reference, note the square brackets in your
Dumper output - $x is an array reference. That's why you get the
warning "Pseudo-hashes are deprecated" and the error "Can't use string
("color") as a HASH ref" (you do have strict and warnings enabled,
right?)
change your foreach to
foreach my $id ( @$x ) {
and you'll see that it operates as you expected. To generate the lists
you desire, you could simply push the type and color onto @type and
@color arrays as you step through your fruit array.
another approach would be to use a different module like XML::Parser
and define a handler for type and color elements to do the same thing.
-jp
.
- Follow-Ups:
- Re: Trouble accessing parsed XML variable
- From: Robert McDonald
- Re: Trouble accessing parsed XML variable
- References:
- Trouble accessing parsed XML variable
- From: Robert McDonald
- Trouble accessing parsed XML variable
- Prev by Date: How good is PERL at searching ASCII files?
- Next by Date: Re: Re: Checking for infinite loops
- Previous by thread: Trouble accessing parsed XML variable
- Next by thread: Re: Trouble accessing parsed XML variable
- Index(es):
Relevant Pages
|