How do I add child elements to XML using Perl's XML::Twig?

只谈情不闲聊 提交于 2020-01-23 14:30:06

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/1259692/how-do-i-add-child-elements-to-xml-using-perls-xmltwig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!