如何使用XML Twig将修改后的树保存到磁盘中

时间:2010-08-19 16:34:58

标签: perl xml-twig

尝试下面这个,但我得到一个0文件,这个错误。 在未打开的文件句柄上打印()在C:/Perl/site/lib/XML/Twig.pm第3036行。

#!c:\perl\bin\perl.exe
use strict;
use XML::Twig;

my $upd_file = "updev.xml" ;
my $main_file = "main.xml" ;

# get the info we need by loading the update file
my $t_upd= new XML::Twig();

$t_upd->parsefile( $upd_file);

my $upd_dev_id = $t_upd->root->next_elt( 'DEVNUM')->text;
my $upd_dev    = $t_upd->root->next_elt( 'DEVS');
my $upd_seg    = $t_upd->root ;

# now process the main file
my $t= new XML::Twig( TwigHandlers => { DEVS => \&DEVS, },
              PrettyPrint => 'indented',
            );
$t->parsefile( $main_file);
$t->flush;           # don't forget or the last closing tags won't be printed

open( OUT, ">$main_file") or die "cannot open out file main_file:$!";

sub DEVS
  { my( $t, $DEVS)= @_;
    # just replace devs if the previous dev_id is the right one
    if( $DEVS->prev_elt( 'DEVNUM')->text eq $upd_dev_id) {
      $upd_dev->replace($DEVS);    
    }
     $t->flush(\*OUT) ;  # print and flush memory so only one dev is in there at once

  }

close OUT ;

1 个答案:

答案 0 :(得分:5)

可能你的问题是你已经传递了文件句柄而不是文件句柄引用。

$t->flush(\*OUT) # look at the '\'

对您的代码提出一些建议:在现代perl中,最好使用三个参数open和indirect filehandles:

open (my $fh_out, '>', $out_file) or die "unable to open '$out_file' for writing: $!";

$twig->print($fh_out); # this prints to the filehandle

另一种打印方式是使用$twig->sprint对树进行字符串化并照常打印到文件句柄

 print {$fh_out} $twig->sprint();