1

我不知道如何使用 Perl 中的 XML::Simple 模块检查节点是否包含值...这是我的代码:

my $parser = XML::Simple->new;
my $url = 'http://some/xml.aspx';
my $content = get $url or die "Unable to get $url\n";
my $data = $parser->XMLin($content);

print "Content-Type: text/html; charset=utf-8\n\n";
foreach my $property (@{$data->{propertyList}}) {
  if ($property->{'boiler'}) {
    print Dumper($property->{'boiler'});
  }
}

一些Boiler节点可以为空,输出如下所示:

$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = {};
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = {};
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = {};
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";
$VAR1 = {};
$VAR1 = "\x{5e9}\x{5de}\x{5e9}";

第四个$VAR1是空的,但我如何在代码中检查它?

先感谢您

4

2 回答 2

2

样本输入会很有用。

当它为“空”时,它是对空哈希的引用,因此:

if ( ref $property->{'boiler'} && eval { keys %{ $property->{'boiler'} } == 0 } ) {
    print "empty";
}

或者您可以将 XML::Simple 的SuppressEmpty选项设置为 1(完全跳过空节点)或 undef 或 ''(让空节点获取该值,而不是对空哈希的默认引用)。正如文档所说,“后两种选择在你的代码中比没有键的哈希更容易测试”。(但请注意,这将影响所有节点,而不仅仅是 Boiler 节点,并且如果您这样做,也会影响 XML 生成。)

于 2013-07-04T19:21:47.577 回答
0
print Dumper($property->{'boiler'}) if $property->{'boiler'} != 0 ;
于 2013-07-04T19:16:26.223 回答