Thursday, September 13, 2007

Parsing XML using XML::Simple

Installing XML::Simple:

shell> perl -MCPAN -e shell cpan> install XML::Simple
Reading XML: You can use XMLin and XMLout to read and write XML file or string.
my $ref = XMLin('/dir/to/file.xml'); # it takes file my $ref2 = XMLin('<xml> .... '); # or string
Example of reading a podcast feed:
#!/usr/bin/perl -w use strict; use warnings; use LWP::Simple; use XML::Simple; use Data::Dumper; my $url = 'http://url/feed.xml'; my $content = get $url; die "Couldn\'t get $url" unless $content; my $ref = XMLin($content); my @items = @{$ref->{'channel'}->{'item'}}; # grabbing link for my $i ( 0 .. $#items ) { print ${$items[$i]}{'link'} . "\n"; }

No comments: