FreeKB - XML Simple in Perl - Printing Attributes
XML Simple in Perl - Printing Attributes

Home > Search
  by

Let's consider this XML file that contains an attributes. In this example, the attributes are name and role.

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

 

The following script will allow you to parse the values from the "name" attribute in the example.xml file. This will print the text "Bugs Bunny" and "Main Character".

#!/usr/bin/perl

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

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

print $xml->{'character'}->{'name'};
print $xml->{'character'}->{'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};
  }
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments