【问题标题】:accessing Multi level xml with perl XML::Simple使用 perl XML::Simple 访问多级 xml
【发布时间】:2014-08-20 16:07:12
【问题描述】:

所有,我已经阅读了许多其他帖子,但无法完全掌握这一点。我正在从 Web 服务中提取数据,并返回以下 XML:

$VAR1 = {
    'error'           => 'EndOfResults',
    'model-responses' => {
        'model' => [
            {   
                'attribute' => {
                    'content' => 'wltvbswfc02',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100540'
            },
            {   
                'attribute' => {
                    'content' => 'wltvsutm1ds02',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100c80'
            },
            {   
                'attribute' => {
                    'content' => 'wltvsdora03',
                    'id'      => '0x1006e'
                },
                'mh' => '0x100c49'
            },
            ]

    },
    'throttle'     => '86',
    'total-models' => '86',
    'xmlns'        => 'http://www.ca.com/spectrum/restful/schema/response'
};

我需要提取“mh”和“content”并分配给一个以内容为键、mh 为值的散列。我无法完全正确地获得数据结构。我感谢任何帮助。 谢谢! 罗伯特

【问题讨论】:

  • 你好罗伯特,欢迎来到 SO。我强烈建议不要在the module's own suggestion 中使用XML::Simple。相反,为了避免XY Problem,请将实际的 XML 代码粘贴到您的问题中,而不是解析后的数据结构,以便获得更好的答案。
  • 米勒:谢谢!我现在看到了这一点,并将查看 XML::libXML,下次我将包含相关代码。再次感谢。

标签: xml perl multi-level


【解决方案1】:

您已经将 XML 转换为 perl 数据结构,所以

use 5.010;
use warnings;
use Data::Dumper;

my $href = {
    "error"           => "EndOfResults",
    "model-responses" => {
        model => [
            {   attribute => { content => "wltvbswfc02", id => "0x1006e" },
                mh        => "0x100540",
            },
            {   attribute => { content => "wltvsutm1ds02", id => "0x1006e" },
                mh        => "0x100c80",
            },
            {   attribute => { content => "wltvsdora03", id => "0x1006e" },
                mh        => "0x100c49",
            },
        ],
    },
    "throttle"     => 86,
    "total-models" => 86,
    "xmlns"        => "http://www.ca.com/spectrum/restful/schema/response",
};

my %res = map { $_->{attribute}{content} => $_->{mh} }
    @{ $href->{"model-responses"}{model} };

say Dumper \%res;

以上打印:

$VAR1 = {
          'wltvsutm1ds02' => '0x100c80',
          'wltvsdora03' => '0x100c49',
          'wltvbswfc02' => '0x100540'
        };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多