tags:

views:

482

answers:

1

I have the following XML file:

<SOURCE_SERVER>
  <SERVER HOSTNAME="serv1">
      <CIFS_SERVICE NETBIOSNAME="serv1"/>
  </SERVER>
  <SERVER HOSTNAME="serv2">
  </SERVER>
<SOURCE_SERVER>

Now, I want to add child <CIFS_SERVICE NETBIOSNAME="serv2"/> to <SERVER HOSTNAME="serv2">. How do I do this using XML::Twig?

+4  A: 

Here is a solution incorporating what I think are reasonable fixes to your question. The code below is based on the filtering example given in the documentation.

#!/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>

Output:

C:\Temp> x
<SOURCE_SERVER>
  <SERVER HOSTNAME="serv1"><CIFS_SERVICE NETBIOSNAME="serv1"/></SERVER>
  <SERVER HOSTNAME="serv2"><CIFS_SERVICE NETBIOSNAME="serv2"/></SERVER>
</SOURCE_SERVER>
Sinan Ünür
Sinan, thanks a ton for your answer. However, I have one more query. Actually my xml looks like this: `<SOURCE_SERVER> <SERVER HOSTNAME="serv1"> <CIFS_SERVICE NETBIOSNAME="serv1"/> </SERVER> <SERVER HOSTNAME="serv2"> <CIFS_SERVICE /> </SERVER> </SOURCE_SERVER>` So, I don't need to insert <CIFS_SERVICE> tag. The twig points to SERVER and I need to set attribute of it's child. How do I do it? Please help me.
Ninja
Thanks a lot for your answer Sinan!
Ninja