views:

848

answers:

1

So I wrote some perl that would parse results returned from the Amazon Web Services. I am using the XML::Simple package. For the most part, everything worked when I pulled out an element. However, the problem I ran into was when an element had an attribute as well. Then I get an error that the item is a Hash.

Here's what I did if I wanted to get the Running Time for a DVD. I just created an item to hold the specific info for this one-off item.

// XML
<ProductGroup>DVD</ProductGroup>
<RunningTime Units="minutes">90</RunningTime>

// Perl to parse XML

my $item = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, ForceArray => ['ASIN']);    

$ProductGroup = $item->{Items}->{Item}->{ItemAttributes}->{ProductGroup};

if(ref($item->{Items}->{Item}->{ItemAttributes}->{RunningTime}) eq 'HASH'){
    $RunningTimeXML = $xml->XMLin($content, KeyAttr => { Item => 'ASIN'}, NoAttr => 1);
    $RunningTime = $RunningTimeXML->{Items}->{Item}->{ItemAttributes}->{RunningTime};
}

Is there a way I can access both elements and attributes from one item?

+4  A: 

$item is a hashref that looks like this:

$item = {
    'RunningTime'  => {'content' => '90', 'Units' => 'minutes'},
    'ProductGroup' => 'DVD'
};

Therefore you can get the running time like this:

$RunningTime = $item->{RunningTime}->{content}
nohat