我只是在学习PERL。我已经阅读了一些关于解析 XML 的文档并重用了我同事的一些代码。但我似乎无法简单地打印出此数据中 3 名足球运动员姓名的列表。请帮忙。这是PERL代码:
#! /usr/bin/perl -w
use strict;
use DBI;
use XML::Simple;
use LWP::UserAgent;
use HTTP::Request;
use Time::gmtime;
use Time::Local;
use Data::Dumper;
sub statsInit(){
my $xml_api_url = "http://myprovider.com/nfldata.xml";
my $xml = getXML($xml_api_url);
my $xmlData = xml2Simple($xml);
print "Hello World";
foreach my $player (@{$xmlData->{player}}){
my $playername = $player->{name};
print "pn = $playername | ";
}
}
sub getXML($){
my ($xmlURL) = @_;
my $dataresponse = '';
my $agent = LWP::UserAgent->new(env_proxy => 1, keep_alive => 1, timeout => 100);
my $header = HTTP::Request->new(GET => $xmlURL);
my $request = HTTP::Request->new('GET', $xmlURL, $header);
my $response = $agent->request($request);
if($response->is_success){
$dataresponse = $response->content(); #Loaded data from FINAL_XML
}
return $dataresponse;
}
sub xml2Simple(){
my ($xml) = @_;
my $xmlObj = XML::Simple->new(KeyAttr => {});
my $xmlData = '';
my $parsedData = '';
if($xml){
$xmlData = $xmlObj->XMLin($xml);
}
return $xmlData;
}
statsInit();
-------- NOW BELOW IS THE RETRIEVED XML DATA --------
<season xmlns="http://myprovider.com/schema/nfl/statistics-v1.0.xsd" season="2012" season_type="REG">
<team id="BUF" name="Bills" market="Buffalo">
<players>
<player id="100" name="Nick Barnett" games_played="1" games_started="1" jersey="50" position="OLB">
<defense tackle="7" ast="2" />
</player>
<player id="101" name="Ryan Fitzpatrick" games_played="1" games_started="1" jersey="14" position="QB">
<rushing att="2" yds="8" />
<passing att="32" cmp="18" yds="195" td="3" int="3"/>
</player>
<player id="102" name="Fred Jackson" games_played="1" games_started="1" jersey="22" position="RB">
<rushing att="6" yds="15" td="0"/>
</player>
</players>
</team>
</season>
所以我的代码似乎可以正常检索数据,并且我没有收到任何错误。“Hello World”被打印出来。但它永远不会进入播放器循环,也不会打印任何播放器名称。我究竟做错了什么?