Parsing XML Elements and Attributes with Perl

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

Here is what I did if I wanted to get Running Time for DVD: I just created an item to store specific information for this one-time 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 to access both elements and attributes from the same element?

+3
source share
1 answer

$item is a hashref that looks like this:

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

Therefore, you can get the runtime as follows:

$RunningTime = $item->{RunningTime}->{content}
+5
source

Source: https://habr.com/ru/post/1696557/


All Articles