【问题标题】:XML::Twig - Inplace editingXML::Twig - 就地编辑
【发布时间】:2015-10-14 10:29:14
【问题描述】:

我正在尝试在 xdp 文件末尾附加时间戳。我正在使用XML::Twig。在运行脚本时,时间戳 (<testing>4619314911532861</testing>) 会在末尾添加,但输出会出现在 STDOUT 而不是 testdata.xdp。我错过了什么?

代码:

#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;

my $twig=XML::Twig->new(pretty_print => 'indented');
my $file = 'testdata.xdp';
$twig->parsefile_inplace($file, '.bak');
my $root= $twig->root;
my @children= $root->children;

foreach my $child (@children){
    my $eblg= new XML::Twig::Elt( 'testing', localtime);
    $eblg->paste( 'last_child', $child);
}

$twig->flush; 

【问题讨论】:

    标签: perl perl-module xml-twig xdp-pdf


    【解决方案1】:

    这里的问题是 - parsefile_inplace 作为一个独立的东西工作。它在parse 操作完成后立即替换源文件。

    因此,要这样使用它,您需要在 twig_handlers 内完成您的“工作”。如果你这样做,它将解析/修改/覆盖。

    例如:

    sub insert_after_all {
        my ( $twig, $element ) = @_;
        my $eblg= new XML::Twig::Elt( 'testing', localtime);
        $eblg->paste( 'last_child', $element);
        $twig -> flush;
    }
    
    my $twig =  XML::Twig->new(pretty_print => 'indented', 
                          twig_handlers => { '_all_' => \&insert_after_all } );
     my $file = 'testdata.xdp';
     $twig->parsefile_inplace($file, '.bak');
    

    否则 - 重命名源和print {$new_fh} $twig -> sprint;

    【讨论】:

    • $twig->flush; 替换为$twig->print。这也将输出扔到 STDOUT。
    • 好的。你能检查一下你的 XML::Twig 版本吗?
    • 最新版本是3.49
    • 啊,不,我看到了问题!这就是parsefile_inplace 的工作方式。编辑答案。
    • 我知道,那个文档不是特别清楚。通过源头快速翻找帮助我弄清楚发生了什么。
    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多