XML::Simple


Let's see some of the parameters controlling the way XML is read into memory by XML::Simple.

XML::Simple is, well, relatively simple but it can still be used in a number of ways. The most straight forward way is to import the XMLin function, and pass a filename to it or a scalar with XML data in it. In addition the XMLin subroutine accepts several options. Two of them are the most important: ForceArray and KeyAttr. Also interesting is KeepRoot.

ForceArray defaults to 0 KeyAttr defaults to ['name', 'key', 'id'] KeepRoot defaults to 0

'Array folding' feature is controlled by KeyAttr


examples/xml/xml_simple_intro.pl
#!/usr/bin/perl
use strict;
use warnings;

use XML::Simple qw(XMLin);
use Data::Dumper;
my $data = <<'END_XML';
<people>
  <person id="1">
     <name>Foo</name>
  </person>
  <person id="2">
     <name>Bar</name>
     <email id="3">bar@home</email>
     <picture src="img.png" />
  </person>
</people>
END_XML

my $xml = XMLin($data,
        ForceArray => 1,
        KeyAttr => [],
        #KeepRoot => 1,
        );

$Data::Dumper::Sortkeys = 1; 
print Dumper $xml;

print "The name of the first  person: $xml->{person}[0]{name}[0]\n";
print "The name of the second person: $xml->{person}[1]{name}[0]\n";

print "The id of the first  person: $xml->{person}[0]{id}\n";
print "The id of the second person: $xml->{person}[1]{id}\n";

print "The id of the first email of the second person: $xml->{person}[1]{email}[0]{id}\n";
print "The first email of the second person: $xml->{person}[1]{email}[0]{content}\n";
print "The srt of the first picture of the second person: $xml->{person}[1]{picture}[0]{src}\n";

# There still is a difference on how to get to the content of an element with attributes
# (the email) and the content of an element without attribute (name).
Without any options this will generate something that is apparently a mess. This is caused by the fact that KeyAttr is trying to be nice and uses the value of the 'name' tag and the 'id' attribute as the keys to the hash it is generating.

examples/xml/xml_simple.pl
#!/usr/bin/perl
use strict;
use warnings;

use XML::Simple;# qw(:strict);
use Data::Dumper;
my $xml = XMLin('examples/data.xml',
        ForceArray => 0, 
        KeyAttr => [],
        );
print Dumper $xml;