Perl (Scripting) - XML::Twig change tag (set_tag)

by
Jeremy Canfield |
Updated: March 19 2021
| Perl (Scripting) articles
Let's say foo.xml contains the following. Notice in this example that the root tag is <food>.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
<name>Apple</name>
</food>
set_tag can be used to change a tag. In this example, the <food> tag will be changed to <html> and the <name> tag will be changed to <fruit>.
parsefile is used to parse XML in a file.
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
my $twig = new XML::Twig(
pretty_print => 'indented',
twig_handlers => {
food => sub { $_->set_tag('html') },
name => sub { $_->set_tag('fruit') },
},
);
$twig->parsefile('foo.xml');
$twig->print;
Did you find this article helpful?
If so, consider buying me a coffee over at