1

我只是在学习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”被打印出来。但它永远不会进入播放器循环,也不会打印任何播放器名称。我究竟做错了什么?

4

2 回答 2

1

我想到了。我想我不得不改变这条线。

foreach my $player (@{$xmlData->{player}}){

对此:

foreach my $player (@{$xmlData->{team}{players}{player}}){  
于 2012-09-14T06:01:36.363 回答
0

另一种选择是绕过将整个文档解析为一个数据结构,并在执行过程中解析、处理和忘记每条记录:

use strict;
use warnings;

use XML::Rules;

my @rules = (
  player => sub {
    my $p = $_[1];
    print "$p->{name}\n";
    return;
  },
  _default => undef,
);
my $xr = XML::Rules->new( rules => \@rules );
$xr->parse($xml);
于 2012-09-26T22:26:09.073 回答