【问题标题】:Parsing XML Elements & Attributes with Perl使用 Perl 解析 XML 元素和属性
【发布时间】:2010-09-07 00:35:23
【问题描述】:

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

如果我想获得 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};
}

有没有一种方法可以同时访问一个项目的元素和属性?

【问题讨论】:

    标签: xml perl amazon-web-services


    【解决方案1】:

    $item 是一个看起来像这样的 hashref:

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

    因此你可以这样得到运行时间:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2011-07-20
      • 2015-02-06
      • 2021-12-13
      • 1970-01-01
      • 2020-12-14
      • 2012-04-03
      • 1970-01-01
      相关资源
      最近更新 更多