如何使用 XML Twig 将修改后的树保存到磁盘中
尝试了下面的方法,但我得到了 0 文件和此错误。 print() 在 C:/Perl/site/lib/XML/Twig.pm 第 3036 行的未打开文件句柄 OUT 上。
#!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 ;
Tried this below but I get a 0 file and this error.
print() on unopened filehandle OUT at C:/Perl/site/lib/XML/Twig.pm line 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 ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题可能是您传递了文件句柄而不是文件句柄引用。
对您的代码的一些建议:在现代 Perl 中,最好使用三个参数打开和间接文件句柄:
另一种打印方式是使用
$twig->sprint
对树进行字符串化,并像往常一样打印到文件句柄Probably your problem is that you have passed the filehandle not a filehandle reference.
Some suggestions for your code: in modern perl is better to use the three arguments open and indirect filehandles:
Another way of printing is stringify your tree with
$twig->sprint
and print to a filehandle as usual