【发布时间】:2016-02-27 18:53:56
【问题描述】:
我正在尝试使用 perl 来解析 XML,但我遇到了一些看起来很奇怪的东西。当我调用 $node->attributes() 在某些情况下它似乎返回一个未定义的值。如果您查看标有问题的行,您可以看到我是否已添加。我会认为,如果节点没有属性,那么 foreach 就不会有任何循环。如果我取消注释该行上的 if 一切正常。 (我知道我可以将检查放在循环之外,但我想知道为什么我需要检查)
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'lib.xml';
use XML::LibXML;
my $parser = XML::LibXML->new();
$parser->keep_blanks(0);
my $doc = $parser->parse_file($filename);
sub process_node {
my $level = shift;
my $node = shift;
printf ("%*s", $level, "");
print $node->nodeName;
print "<", $node->nodeValue,">" if (defined($node->nodeValue));
print "\n";
print "attrs:\n";
foreach ($node->attributes()){
print $_->name,":",$_->value," " ;# if (defined($_)); ### problem
}
print "\n";
for my $child ($node->childNodes) {
process_node($level+1, $child);
}
}
process_node(1, $doc->documentElement);
这是 lib.xml 的内容:
<data size="4">
<stuff src="one" dst="two" />
hmm
</data>
这是“坏”的输出:
>>> ./xml.pl
data
attrs:
size:4
stuff
attrs:
src:one dst:two
text<
hmm
>
attrs:
Can't call method "name" on an undefined value at ./xml.pl line 26.
当我取消对 if 的注释时会很好
>>> ./xml.pl
data
attrs:
size:4
stuff
attrs:
src:one dst:two
text<
hmm
>
attrs:
【问题讨论】: