I can hardcode and retrieve the value of childtag "title"
i.e my @attr= $root->{entry}->[0]->{title}->[0];
print $attr[0];
prints desired result i.e "ccc"
I need to know how can i retrieve it dynamically i.e instead of "0" i need to use some variable which can keep track of "entry" present in response
i need something like
my @attr= $root->{entry}->[i]->{title}->[i];
Can anyone please tell me
[edited by: PankajBansal at 5:41 am (utc) on June 9, 2009]
you probably want to use a scalar variable as an index for the array.
for example:
for ($i=0; $i<@$root->{entry}; $i++)
{
...
my @attr = $root->{entry}->[$i]->{title}->[0];
...
}
welcome to perl as well - there are several resources listed in the Perl Server Side CGI Scripting forum Charter [webmasterworld.com] which will help you understand and use perl.
i should also mention that it looks like your xml sample is not "well formed", so that may cause some problems.
you may wish to seek further help with that in the XML Development [webmasterworld.com] forum or perhaps in this case the RSS, ATOM, and Related Technologies [webmasterworld.com] forum.
If you are going to be doing a lot of XML parsing and you want it to be flexible, you might want to consider one of the available perl XML libraries such as XML::LibXML to help you out. You could do something like this:
my $parser = XML::LibXML->new();
my $tree = $parser->parse_string($xml, {recover=>1});
my $root = $tree->getDocumentElement;
my @titles = $root->getElementsByTagName('Title');
foreach my $data (@titles) {
my $title = $data->getFirstChild->getData;
}
**Note that in the above, $xml is the XML data passed into the LibXML parser. Depending on where you are getting it from (flat-file, code generated, API response, etc.), that might affect how you need to 'prepare' it for parsing and passing in as the $xml variable.