xml - 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 引用
这是为什么?
解决方案
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});
推荐阅读
- spring - 从异步 http 调用传递状态而不阻塞线程
- lstm - 使用 RNN/LSTM 进行预测时的隐藏状态是什么?
- azure-devops - 有没有办法让这个更新构建的管道变量?
- google-cloud-platform - 写入已挂载的文件系统时出现 OSError 输入/输出错误
- heroku - Flask route /predict 在返回对象上返回名称错误
- django - How to properly create JSON arrays from two database table using Django
- sql - 成本较低的 SQL 查询比成本较高的查询运行得慢
- python - 需要帮助弄清楚为什么每行都出现随机字符
- c# - Differences between Parallel.ForEach and await ForEachAsync
- javascript - Resolve a function that uses Promise