2

我有以下 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执行此操作?

4

1 回答 1

5

这是一个解决方案,其中包含我认为对您的问题的合理解决方案。下面的代码基于文档中给出的过滤示例。

#!/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>
于 2009-08-11T11:43:30.447 回答