Perl XML::LibXML getting the Nth element -
here simplified sample xml
<book_reviewers> <results> <reviewer> <name>anne</name> <profession>catfish wrangler</profession> </reviewer> <reviewer> <name>bob</name> <profession>beer taster</profession> </reviewer> <reviewer> <name>charlie</name> <profession>gardener</profession> </reviewer> <reviewer> <name>don</name> <profession>dogooder</profession> </reviewer> <reviewer> <name>ellie</name> <profession>elephant trainer</profession> </reviewer> <reviewer> <name>freddy</name> <profession>fencer</profession> </reviewer> </results> </book_reviewers>
them parse data
#!/usr/bin/perl use xml::libxml; use strict; $filename = "cr.xml"; $parser = xml::libxml->new(); $critic_details = $parser->parse_file("$filename") or die;
now want grab details of random reviewer
my $no_of_critics = ($critic_details->findvalue("count(/book_reviewers/results/reviewer)"));
i send number 1 , $no_of_critics off subroutine returns random number between 1 , $no_of_critics (i.e. n case 1 , 6)
all of works fine need know how tell reviewer - returns 5, how tell want fifth occurrence of reviewer? have tried searching cannot right search term bit stuck
cheers
building on top of yu had in previous question:
use strict; use warnings; use utf8; use xml::libxml; $filename = "cr.xml"; $parser = xml::libxml->new(); $critic_details = $parser->parse_file("$filename") or die; # find <book_reviewers><results><reviewers> nodes @reviewers = $critic_details ->findnodes("book_reviewers/results/reviewer"); die "no reviewer nodes in xml-file" unless @reviewers; # @reviewers in scalar context gives number of elements $reviewer = $reviewers[ rand @reviewers ]; printf "reviewer: %s (%s)\n", $reviewer->findvalue("name"), $reviewer->findvalue("profession"), ; __end__
which result in:
reviewer: anne (catfish wrangler)
enjoy!
Comments
Post a Comment