Re: Trouble accessing parsed XML variable



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

.



Relevant Pages

  • Re: How to calculate: sumproduct / db??
    ... returns an array of TRUE/FALSE values. ... single unary, -, transforms the TRUE/FALSE to 1/0, but a negative 1. ... number of pieces fruit in a box ...
    (microsoft.public.excel.programming)
  • Re: Multiple ComboBoxes, one data source
    ... have to make sure that each combobox uses a separate BindingContext. ... You could also get around this by copying the contents of the array into ... Fruit 2: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Multiple ComboBoxes, one data source
    ... You could also get around this by copying the contents of the array into ... Fruit 1: ... I have set the datasource on all the comboBoxes to be fruitList ... I want to make fruit 1 an apple, fruit 2 a bannana and fruit 3 a pear, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Enumerations
    ... > So, way back when I was first learning how to program, I think I used Pascal ... enum fruit {APPLE, BANANA, CARROT, NUM_FRUITS}; ... But add a name (and carrots aren't a fruit:) ... but you got rid of my array. ...
    (comp.lang.lisp)
  • Re: Food and our 9 month old
    ... The first question I have is what to do about fruit? ... When you let him feed himself, do you just let him finger feed himself ... I fed my children eggs prior to a year, but we didn't have any food ... is fine for baby to feed himself with supervision. ...
    (misc.kids)