Bootstrap FreeKB - Perl (Scripting) - XML::Twig change value (set_text)
Perl (Scripting) - XML::Twig change value (set_text)

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 27696c in the box below so that we can be sure you are a human.