Display a list of the available parsers using Perl
#!/usr/bin/perl use XML::SAX; use strict; my @parsers = @{XML::SAX->parsers()}; foreach my $parser (@parsers) { print "--> ", $parser->{ Name }, "\n"; }
Output:
–> XML::LibXML::SAX::Parser
–> XML::LibXML::SAX
–> XML::SAX::Expat
Using Data::Dumper to display XML in Perl
Input XML:
<?xml version="1.0"?> <customer-data> <customer> <first_name>mani</first_name> <last_name>reddy</last_name> <dob>3/10</dob> <email>mani@w3mentor.com</email> </customer> <customer> <first_name>deva</first_name> <last_name>chauhan</last_name> <dob>4/15</dob> <email>pdeva@w3mentor.com</email> </customer> </customer-data>
Dumping using Data::Dumper
#!/usr/bin/perl use strict; use XML::Simple; use Data::Dumper; my $xml = XMLin('./input.xml',forcearray => 1); print Dumper($xml);
Unformatted Output:
$VAR1 = {
‘customer’ => [
{
'email' => [
'mani@w3mentor.com'
],
‘dob’ => [
'3/10'
],
‘last_name’ => [
'reddy'
],
‘first_name’ => [
'deva'
]
},
{
‘email’ => [
'pdeva@w3mentor.com'
],
‘dob’ => [
'4/15'
],
‘last_name’ => [
'chauhan'
],
‘first_name’ => [
'Sandy'
]
}
]
};
Parsing XML with XML::Simple in Perl
XML::Simple is an example of a tree-based XML parser, which is, well, simpler to use than other XML parsers. XML::Simple has just two subroutines: XMLin() and XMLout(). XMLin() is used to read an XML structure into an in-memory hash. The source of this XML is usually a string or file. From the XMLin() subroutine comes a reference to a hash. XMLout() creates XML when passed a reference to a hash that contains an encoded document.
Input XML:
<?xml version="1.0"?> <customer-data> <customer> <first_name>mani</first_name> <last_name>reddy</last_name> <dob>3/10</dob> <email>mani@w3mentor.com</email> </customer> <customer> <first_name>deva</first_name> <last_name>chauhan</last_name> <dob>4/15</dob> <email>pdeva@w3mentor.com</email> </customer> </customer-data>
Parsing the XML:
#!/usr/bin/perl use strict; use XML::Simple; my $xml = XMLin('./input.xml',forcearray => 1); foreach my $customer (@{$xml->{customer}}) { print "Name: $customer->{first_name}->[0] "; print "$customer->{last_name}->[0]\n"; print "Birthday: $customer->{dob}->[0]\n"; print "E-mail Address: $customer->{email}->[0]\n"; }
Output:
Name: mani reddy
Birthday: 3/10
E-mail Address: mani@w3mentor.com
Name: deva chauhan
Birthday: 4/15
E-mail Address: pdeva@w3mentor.com
