XML::Twig - 就地编辑

XML::Twig - Inplace editing

我正在尝试在 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; 

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

因此,要像那样使用它,您需要在 twig_handlers 内完成 'work'。如果你这样做,它会 parse/modify/overwrite。

例如:

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;