Perl (Scripting) - XML::Twig change value (set_text)
                
            
            
            
             
            
            
                           
                
            
            
            
                
    
    
     
            
                
                    by
                    Jeremy Canfield  |  
                    Updated: March 19 2021
                    
                          |  Perl (Scripting) articles
                    
                    
                    
                
            
            Let's say foo.xml contains the following.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <name>Apple</name>
</food>
set_text can be used to change Apple to Orange.
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $twig = new XML::Twig( pretty_print => 'indented' );
$twig->parse('<?xml version="1.0" encoding="UTF-8" standalone="no"?><acme><name>Bugs Bunny</name></acme>');
foreach my $name ($twig->root->children('name')) {
  $name->set_text('Orange');
}
$twig->print;
Which should return the following.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <name>Orange</name>
</food>
If you want, you could also output the updated XML to a file.
my $file = "/path/to/bar.xml";
if (open my $fh, ">", $file) {
  $twig->print($fh);
  close $fh;
}
else {
  print "failed to open $file \n";
  exit 1;
}
Did you find this article helpful?
If so, consider buying me a coffee over at 