【问题标题】:perl with xml : why to I need check if the Attribute is defined, shouldn't $node->attributes already do that?perl with xml:为什么我需要检查属性是否已定义,不应该 $node->attributes 已经这样做了吗?
【发布时间】: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:

【问题讨论】:

    标签: xml perl


    【解决方案1】:

    这是因为我认为 XML::LibXML::Text::attributes 中存在一个错误,看起来像这样

    sub attributes { return undef; }
    

    这应该是

    sub attributes { return }
    

    这将在标量上下文中返回undef,在列表上下文中返回一个空列表

    如果你愿意,你可以自己修复它。在最新版本的模块中——2.0123——它位于XML::LibXML 安装中LibXML.pm 的第1789 行。你可以通过运行发现文件在哪里

    perldoc -l XML::LibXML
    

    我会向维护者提出错误报告

    【讨论】:

    • 我会看看这个。谢谢
    • @kdubs:我已经收到了图书馆维护人员的回复。正如我在此处所写的那样,该修复程序已合并到版本 2.0124 中,并且一旦上传就可以在 CPAN 上使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多