0

I have XML from this link http://sapxi.dfssi.com/parser/book.xml

I want to get values from the first book element. Any idea how to parse it in Perl?

use strict;
use warnings;

use Data::Dumper;
use XML::Simple;
use LWP::Simple;

my $parser = new XML::Simple;

my $url = 'http://sapxi.dfssi.com/parser/book.xml';
my $content = get $url or die "Unable to get $url\n";
my $data = $parser->XMLin($content);

print Dumper($data);
print $data->{book}{title}->[0];

I always get

Not a HASH reference at ./xml_parser.pl line 20.

All I want is to print the title Book 1 title and the author value.

Output will be like this.

Book title: Book 1 title Author: Book 1 author 1, Book 1 author 2

Thanks in advance for helping.

it should be print $data->{book}->[0]->{title};

Borodin
  • 126,100
  • 9
  • 70
  • 144
vher
  • 21
  • 11
  • solve it already hahaha. – vher May 09 '16 at 04:31
  • 2
    If you have a solution then you should post it as an answer below. Also, *please* don't use `XML::Simple`: [*Why is XML::Simple "Discouraged"?*](http://stackoverflow.com/questions/33267765/why-is-xmlsimple-discouraged) – Borodin May 09 '16 at 04:48
  • Please take a look at [*What should I do when someone answers my question?*](http://stackoverflow.com/help/someone-answers) – Borodin May 09 '16 at 19:18

1 Answers1

3

Here's a solution using XML::LibXML. XML::Twig is a good alternative that you may prefer

use strict;
use warnings 'all';

use XML::LibXML;

use constant XML_URL => 'http://sapxi.dfssi.com/parser/book.xml';

my $doc = XML::LibXML->load_xml(location => XML_URL);

my ($book_1) = $doc->findnodes('/booklist/book[1]');

my ($title) = $book_1->findnodes('title[1]');
my @authors = $book_1->findnodes('author');

printf "Book title: %s Author: %s\n",
        $title->textContent,
        join(', ', map $_->textContent, @authors);

output

Book title: Book 1 title Author: Book 1 author 1, Book 1 author 2
Borodin
  • 126,100
  • 9
  • 70
  • 144