首页 > 解决方案 > XML::裸力数组

问题描述

我正在尝试解析以下 XML 数据 XML::Bare

<xml>
  <a>
    <b>1</b>
    <b>2</b>
    <c>
      <b>3</b>
    </c>
  </a>
  <a>
    <b>4</b>
    <c>
      <b>5</b>
      <b>6</b>
    </c>
    <c>
      <b>7</b>
    </c>
  </a>
</xml>

使用以下代码:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Bare qw( forcearray );

my $ob   = new XML::Bare( file => "tst.xml" );
my $root = $ob->parse();

forcearray($root->{xml}->{a});
my @as = @{ $root->{xml}->{a} }

foreach ( @as ) {

    print $ob->xml($_);

    forcearray($_->{b});
    print scalar @{ $_->{b} }, " bs\n";

    forcearray($_->{c});
    print scalar @{ $_->{c} }, " cs\n";
}

它在最后一次打印时失败

不是 ./tst_xml.pl 第 16 行的 ARRAY 引用

这是为什么?

标签: xmlperl

解决方案


sub forcearray {
  my $ref = shift;
  return [] if( !$ref );
  return $ref if( ref( $ref ) eq 'ARRAY' );
  return [ $ref ];
}

XML::Bare::forcearray函数始终返回一个数组引用,但它不会修改其输入。所以你需要使用的返回值forcearray

$_->{b} = forcearray($_->{b});
$_->{c} = forcearray($_->{c});

推荐阅读