如何使用Perl的XML :: Twig将子元素添加到XML?

时间:2009-08-11 11:07:47

标签: xml perl xml-twig

我有以下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

执行此操作

1 个答案:

答案 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>