我有以下XML文件:
<SOURCE_SERVER>
<SERVER HOSTNAME="serv1">
<CIFS_SERVICE NETBIOSNAME="serv1"/>
</SERVER>
<SERVER HOSTNAME="serv2">
</SERVER>
<SOURCE_SERVER>
现在,我想将子<CIFS_SERVICE NETBIOSNAME="serv2"/>
添加到<SERVER HOSTNAME="serv2">
。如何使用XML::Twig?
答案 0 :(得分:5)
这是一个解决方案,包含我认为对您的问题的合理修复。以下代码基于文档中提供的filtering example。
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $t = XML::Twig->new(
twig_roots => { SERVER => \&update },
twig_print_outside_roots => 1,
);
$t->parse(\*DATA);
sub update {
my ($t, $server) = @_;
if ( 'serv2' eq $server->att('HOSTNAME') ) {
$server->insert(
CIFS_SERVICE => { NETBIOSNAME => 'serv2' },
);
}
$server->print;
}
__DATA__
<SOURCE_SERVER>
<SERVER HOSTNAME="serv1">
<CIFS_SERVICE NETBIOSNAME="serv1" />
</SERVER>
<SERVER HOSTNAME="serv2">
</SERVER>
</SOURCE_SERVER>
输出:
C:\Temp> x
<SOURCE_SERVER>
<SERVER HOSTNAME="serv1"><CIFS_SERVICE NETBIOSNAME="serv1"/></SERVER>
<SERVER HOSTNAME="serv2"><CIFS_SERVICE NETBIOSNAME="serv2"/></SERVER>
</SOURCE_SERVER>