Last Updated: July 25, 2019
·
14.5K
· syxanash

Easily parse XML with Perl

To easily parse XML in Perl I use XML::Simple. This is quite useful if you want, to parse the response of a request to a website which allows you to use an API system, such as Imageshack in my case.

For example, let's write a piece of XML code like the following one:

<booklist>
    <author>George Orwell</author>
    <book>    
        <title>Animal Farm</title>
        <year>1945</year>
        <language>English</language>
        <country>United Kingdom</country>
    </book>
</booklist>

now let's see how Perl can transform the previous XML code into a Perl hash:

use strict;
use warnings;

use XML::Simple;

my $xml = q{<booklist>
    <author>George Orwell</author>
    <book>    
        <title>Animal Farm</title>
        <year>1945</year>
        <language>English</language>
        <country>United Kingdom</country>
    </book>
</booklist>};

my $data = XMLin($xml);

for example let's print the title of the book:

print $data->{book}{title}, "\n"

or if you want to see the whole content of $data with Data::Dumper just type:

print Dumper( $data ), "\n";

pretty easy right?