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.

#!/usr/bin/perl
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>');
$twig->print;

 

The following should be returned.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food><name>Apple</name></food>

 

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"?>
<food>
  <name>Apple</name>
</food>

 

parsefile is used to parse XML in a file.

my $twig = new XML::Twig;
$twig->parsefile('foo.xml');
$twig->print;

 

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

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

 

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



Comments


Add a Comment


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