【问题标题】:Can not locate object via package XML::Twig无法通过包 XML::Twig 定位对象
【发布时间】:2016-02-06 03:56:55
【问题描述】:

我正在尝试使用以下脚本将 xml 文件转换为 csv

#!/usr/local/bin/perl 
use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new()->parsefile ( 'test.xml' );

print "id;name;description;published\n";
foreach my $row ( $twig->results->children('row') ) {        
        print join( ";",
            $row->first_child_text('id'),
            $row->first_child_text('name'),
            $row->first_child_text('description'),
            $row->first_child_text('published'),
),
            "\n";

}

但我在 perl1.pl 第 10 行通过包“XML::Twig”收到错误 Can't locate object method "results”。

这是我的 xml

<results>
  <row>
    <id></id>
    <name>...</name>
    <description>...</description>
    <published></published>
</row>
....
</result>

【问题讨论】:

    标签: xml perl csv


    【解决方案1】:

    告诉你问题 - 就是这一行:

    foreach my $row ( $twig->results->children('row') ) {   
    

    没有“结果”方法。你可能想要:

    foreach my $row ( $twig->root->children('row') ) {   
    

    root 方法访问“文档根”——在本例中是 XML 的“结果”元素。

    您也可以在//row 上使用get_xpath 来查找文档中任意位置的所有“行”元素。

    作为一个风格点 - 尽可能避免重复是可取的 - 所以考虑到这一点,我建议:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use XML::Twig;
    
    my @cols = qw ( id name description published );
    
    my $twig = XML::Twig->parsefile('test.xml');
    
    print join( ";", @cols ), "\n";  #header row
    foreach my $row ( $twig->get_xpath('//row') ) {
        print join( ";", map { $row->first_child_text($_) } @cols ), "\n";
    }
    

    【讨论】:

    • 现在我得到这个错误 Can't use string ("XML::Twig") as a HASH ref while "strict refs" in use at /usr/local/lib/x86_64-linux-gnu /perl/5.20.2/XML/Parser.pm 第 224 行。在 perl1.pl 第 6 行。
    • 好的。无法回答为什么,没有看到一些代码。但是......你的代码中有use XML::Twig;吗?因为这通常表示没有加载模块。
    • 提出一个新问题,发布代码和错误。我相信有人会回答它(可能是我)。我已经测试了上面的示例,这绝对有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    相关资源
    最近更新 更多