Bootstrap FreeKB - Perl (Scripting) - XML::Simple Printing Attributes
Perl (Scripting) - XML::Simple Printing Attributes

Updated:   |  Perl (Scripting) articles

Let's consider this XML file that contains an attribute.

<acme>
  <name role="main">Bugs Bunny</character>
</acme>

 

 

The following is how to print the value of an attribute. In this example, "main" will be printed.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

my $xml = XMLin("example.xml");

print $xml->{'name'}->{'role'};

 


Multiple lines

If your XML file will have two or more lines with an identical key, you will need to use a foreach loop. In this example, there are two lines that both contain the "character" key.

<acme>
  <character name="Bugs Bunny" role="Main Character"></character>
  <character name="Elmer Fudd" role="Support Character"></character>
</acme>

 

The following script will allow you to parse the values from the example.xml file.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

my $xml = XMLin("example.xml");

foreach my $character ( keys %{$xml} ) {
  foreach my $name ( keys %{$xml->{$character}} ) {
    print "$name\n";
  }
}

 

To print each role.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

my $xml = XMLin("example.xml");

foreach my $character ( keys %{$xml} ) {
  foreach my $name ( keys %{$xml->{$character}} ) {
    print $xml->{$character}->{$name}->{role};
  }
}

 




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