Bootstrap FreeKB - Perl (Scripting) - XML::Twig print attributes
Perl (Scripting) - XML::Twig print attributes

Updated:   |  Perl (Scripting) articles

Let's say foo.xml contains the following.

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

 

Here is how you would parse foo.xml and print the XML tags using XML::Twig.

#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;

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

 

The following should be returned.

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

 

And here is how you would print the value of the "name" attribute.

foreach my $name ($twig->root->first_child('fruit')->att('name')) {
  print $name;
}

 

Which should return the following.

Apple

 




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 f21fe9 in the box below so that we can be sure you are a human.