Bootstrap FreeKB - Perl (Scripting) - XML::Twig parse XML
Perl (Scripting) - XML::Twig parse XML

Updated:   |  Perl (Scripting) articles

parse is used to store XML in a variable named $twig.

use strict;
use warnings;
use XML::Twig;

my $twig = new XML::Twig;
$twig->parse('<?xml version="1.0" encoding="UTF-8" standalone="no"?><food><name>Apple</name></food>');


The following should be returned.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>


Notice that the XML is inline instead of indented. pretty_print can be used to indent the output.

my $twig = new XML::Twig( pretty_print => 'indented' );


Now the output should be indented.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>


parsefile is used to parse XML in a file.

my $twig = new XML::Twig;


children can be used to only print the <name> tags.

foreach my $name ($twig->root->children('name')) {


Which should return the following.

  <name>Bugs Bunny</name>


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee


Add a Comment

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