1

I can't figure out how to check if node contains value with XML::Simple module in Perl... Here is the my code:

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'});
  }
}

Some of Boiler nodes can be empty and the output looks like that:

$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}";

The fourth $VAR1 is empty but how can I check it in code??

Thank you in advance

ysth
  • 96,171
  • 6
  • 121
  • 214
nKognito
  • 6,297
  • 17
  • 77
  • 138

2 Answers2

2

Sample input would have been useful.

When it is "empty", it is a reference to an empty hash, so:

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

Or you could set XML::Simple's SuppressEmpty option to 1 (to skip empty nodes altogether) or to undef or '' (to have empty nodes get that value instead of the default reference to an empty hash). As the documentation says, "the latter two alternatives are a little easier to test for in your code than a hash with no keys". (But note that this will affect all nodes, not just Boiler nodes, and also has an effect on XML generation if you are doing that.)

ysth
  • 96,171
  • 6
  • 121
  • 214
0
print Dumper($property->{'boiler'}) if $property->{'boiler'} != 0 ;
jacktrade
  • 3,125
  • 2
  • 36
  • 50
  • 1
    `if $property->{'boiler'} == 0` to check if not empty)) Thanks! – nKognito Jul 04 '13 at 19:26
  • 1
    no, that is completely wrong. it tests if the numeric value is 0 (which it will happen to be for all the "non-empty" strings in the example, with a warning if warnings are enabled). – ysth Jul 04 '13 at 20:14