使用Perl解析XML元素和属性

时间:2022-12-01 11:00:06

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.

所以我写了一些perl来解析从Amazon Web Services返回的结果。我正在使用XML :: Simple包。在大多数情况下,当我拿出一个元素时,一切都有效。但是,我遇到的问题是元素也有属性。然后我得到一个错误,该项目是哈希。

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.

如果我想获得DVD的运行时间,我就是这样做的:我刚创建了一个项目来保存这个一次性项目的具体信息。

// 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?

有没有办法可以从一个项目中访问元素和属性?

1 个解决方案

#1


5  

$item is a hashref that looks like this:

$ item是一个如下所示的hashref:

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

Therefore you can get the running time like this:

因此,您可以像这样获得运行时间:

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

#1


5  

$item is a hashref that looks like this:

$ item是一个如下所示的hashref:

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

Therefore you can get the running time like this:

因此,您可以像这样获得运行时间:

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