2010-11-09 30 views
0

(操作系統Pro中,的ActivePerl 5.10.1和XML-SAX 0.96使用)XML-SAX錯誤:沒有一個數組引用

MyXML.xml因爲這

<?xml version="1.0" standalone="yes"?> 
<DocumentElement> 
    <subItem> 
    <bib>0006</bib> 
    <name>Stanley Cheruiyot Teimet</name> 
    <team>肯尼亞</team> 
    <time>2:17:59</time> 
    <rank>1</rank> 
    <comment /> 
    <gender>Male</gender> 
    <distance>Full</distance> 
    <year>2010</year> 
    </subItem> 
</DocumentElement> 

MyPerl.pl

#!/usr/bin/perl -w 
use strict; 
use XML::Simple; 
use Data::Dumper; 
use utf8; 

open FILE, ">myXML.txt" or die $!; 

my $tree = XMLin('./myXML.xml'); 
print Dumper($tree); 

print FILE "\n"; 

for (my $i = 0; $i < 1; $i++) 
{ 
    print FILE "('$tree->{subItem}->[$i]->{distance}')"; 

} 

close FILE; 

輸出:

D:\learning\perl\im>mar.pl 
$VAR1 = { 
      'subItem' => { 
         'distance' => 'Full', 
         'time' => '2:17:59', 
         'name' => 'Stanley Cheruiyot Teimet', 
         'bib' => '0006', 
         'comment' => {}, 
         'team' => '肯尼亞', 
         'rank' => '1', 
         'year' => '2010', 
         'gender' => 'Male' 
         } 
     }; 
Not an ARRAY reference at D:\learning\perl\im\mar.pl line 41. 

我不知道是什麼個數組引用意味着什麼? Dumper()工作正常。但不能將數據打印到TXT文件。

實際上,示例代碼在幾天前運行良好,然後我記得我從V5升級了我的Komodo Edit。到最新的V6。

今天,我只是試圖改進腳本,在開始階段,我修復了另一個錯誤。 「無法找到ParserDetails.ini」谷歌幫助。 (我沒有得到錯誤!)

但現在我得到ARRAY參考錯誤。我剛剛通過PPM重新安裝了我的XML-SAX。它仍然不起作用。

回答

3

您設置的XML解析的整個堆棧工作正常,因爲解析樹的轉儲顯示。 XML :: SAX不是問題的原因,它只是間接涉及的。

錯誤來自於對XML :: Simple生成的數據結構的不正確訪問。

我可以猜到發生了什麼事。在程序的早期版本中,啓用了ForceArray選項(這是一種很好的做法,請參閱XML :: Simple中的OPTIONSSTRICT_MODE),並且還會編寫用於遍歷解析樹的算法,以考慮這一點。涉及到數組訪問。

在程序的當前版本ForceArray未啓用,但遍歷算法不再與數據結構匹配。我建議重新啓用文檔中建議的選項。

#!/usr/bin/env perl 
use utf8; 
use strict; 
use warnings FATAL => 'all'; 
use IO::File qw(); 
use XML::Simple qw(:strict); 
use autodie qw(:all); 

my $xs = XML::Simple->new(ForceArray => 1, KeyAttr => {}, KeepRoot => 1); 
my $tree = $xs->parse_file('./myXML.xml'); 

{ 
    open my $out, '>', 'myXML.txt'; 
    $out->say; 
    for my $subitem (@{ $tree->{DocumentElement}->[0]->{subItem} }) { 
     $out->say($subitem->{distance}->[0]); # 'Full' 
    } 
} 

樹看起來像現在這樣:

{ 
    'DocumentElement' => [ 
     { 
      'subItem' => [ 
       { 
        'distance' => ['Full'], 
        'time'  => ['2:17:59'], 
        'name'  => ['Stanley Cheruiyot Teimet'], 
        'bib'  => ['0006'], 
        'comment' => [{}], 
        'team'  => ["\x{80af}\x{5c3c}\x{4e9a}"], 
        'rank'  => ['1'], 
        'year'  => ['2010'], 
        'gender' => ['Male'] 
       } 
      ] 
     } 
    ] 
} 
+0

先生您好,您的代碼工作得很好。最後,我發現我的原始代碼也適用於只有用Caps Letters命名的Xml element subItem。像* bib * - > * Bib *; *姓名* - > *姓名*。 Bib和Name來自我的Excel文件。我不知道特殊的Caps Naming規則。這就是我遇到這種麻煩的原因。無論如何,謝謝你,你教過我'FourceArray'。 – 2010-11-11 05:16:26