Forum Moderators: coopster & phranque

Message Too Old, No Replies

Parsing XML

A Little Help Required

         

StanTheMan

2:48 pm on Mar 30, 2005 (gmt 0)

10+ Year Member



Can any one tell me how to get parse data out of a XML document and store them in variables?

I understand this is basic but I am a basic kinda guy!

Thanks

moltar

3:13 pm on Mar 30, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Have a look at XML::Simple [search.cpan.org]. It may look very complex at first, but in reality it's very simple.

It does not come with Perl by default. You need to install it yourself.

wruppert

3:26 am on Mar 31, 2005 (gmt 0)

10+ Year Member



Here is the essence of a routine I recently wrote to access a certain web service. Details have been obscured.

Note the eval. XMLin dies if the parse fails - the eval protects against that.

You can use Data::Dumper to see the details of the hash of hashes the XML is parsed into as a guide to figuring out how to get at it.

I had my own "get" subroutine in my code, so I had to avoid importing the "get" routine in LWP::Simple.

My real code returned undef instead of croaking.

[pre]
use strict;
use warnings;
use Carp;
use LWP::Simple qw(!get);
use XML::Simple;
use Data::Dumper;

my $debug = 1;

my $url =
"http://engine.exampleapi.com/api.xml" .
"?application=sample_ap" .
"&key1=" . $key1_value .
"&key2=" . $key2_value;

my $xml = LWP::Simple::get($url);
croak "get $url failed" unless $xml;

my $results = eval{XMLin($xml)};
if($@) {
croak "XML Parse failed: $@\n";
}

if ($debug) {
print "\nget XML Parse:\n";
print Dumper($results), "---------------\n";
}

print $results->{foo1}->{bar1}, "\n";
print $results->{foo1}->{bar2}, "\n";
print $results->{foo2}->{bar1}, "\n";
print $results->{foo2}->{bar2}, "\n";
[/pre]