FreeKB - XML Simple in Perl - Getting Started
XML Simple in Perl - Getting Started

Home > Search


Let's consider this XML.

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

 

 


Keys

XML:Simple can be used to do something with keys (name). In this example, "name" will be printed.

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

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

foreach my $key (keys %{$xml}) {
  print "$key\n";
}

 


Values

XML:Simple can be used to do something with values (Bugs Bunny). In this example, "Bugs Bunny" will be printed.

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

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

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

 


Attributes

XML:Simple can be used to do something with attributes (role="main"). 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'};

 


Data::Dumper

Data::Dumper can be used to understand how XML::Simple is interpreting the XML. Here is an example of how to use Data::Dumper.

#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

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

 

Which will produce the following.

  • "name" is the root key
  • "content" and "role" are child keys below the root key
  • "Bugs Bunny" is a value of the "content" key
  • "main" is a value of the "role" key 
  • Data inside of { } is interpreted as a hash
$VAR1 = {
          'name' => {
                     'content' => 'Bugs Bunny',
                     'role' => 'main'
               }
        };

 

Let's consider this XML.

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

 

Data::Dumper now has the [ ] characters. Data inside of [ ] is interpreted as an array.

$VAR1 = {
          'name' => [
                    {
                     'content' => 'Bugs Bunny',
                     'role' => 'main'
                    },
                     'content' => 'Elmer Fudd',
                     'role' => 'support'
                    }
                  ]
        };

 

Now, the following would . . .

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

 

. . . return the following stderr, because $xml->name->content points to both Bugs Bunny and Elmer Fudd.

Not a HASH reference

 


Hash

Data is considered a hash when the key contains a single piece of data, like this.

$xml->name->content = Bugs Bunny

 


Array

Data is considered an array when there are two or more identical keys, like this.

$xml->name->content = Bugs Bunny
$xml->name->content = Elmer Fudd

 

 



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




Comments