2010-11-27 60 views
1

部分看起來是這樣的:XML :: Twig忽略了一些元素?該XML的

<ipcEntry kind="1" symbol="A01B0013080000" ipcLevel="A" entryType="K" lang="EN" nocore="yes"> 
    <textBody> 
     <title> 
      <titlePart> 
       <text>for working subsoil</text> 
      </titlePart> 
     </title> 
    </textBody> 
    <ipcEntry kind="2" symbol="A01B0013100000" ipcLevel="A" entryType="K" lang="EN" nocore="yes"> 
     <textBody> 
      <title> 
       <titlePart> 
        <text>Special implements for lifting subsoil layers</text> 
       </titlePart> 
      </title> 
     </textBody> 
     <ipcEntry kind="3" symbol="A01B0013120000" ipcLevel="A" entryType="K" lang="EN" nocore="yes"> 
      <textBody> 
       <title> 
        <titlePart> 
         <text>Means for distributing the layers on the surface</text> 
        </titlePart> 
       </title> 
      </textBody> 
     </ipcEntry> 
    </ipcEntry> 
</ipcEntry> 

我的代碼是:

#!/usr/bin/perl 
use strict; 
use warnings; 
use XML::Twig; 
use Data::Dumper; 

my $twig_handlers = { 'ipcEntry' => \&ipcEntrySub }; 

my $file = 'A01B.xml'; 
my $twig= new XML::Twig(twig_handlers => $twig_handlers); 
$twig->parsefile($file); 
#$twig->print; 




sub ipcEntrySub { 

    my ($twig_obj, $element) = @_; 

    print $element->{'att'}->{'symbol'} . "\n"; 
print "Kind: $element->{'att'}->{'kind'}\n"; 
print $element->text . "\n"; 
print "###########################################\n"; 


    $twig_obj->purge; 

} 

好像我不能讓文字:<text>Special implements for lifting subsoil layers</text> 我想它,因爲<ipcEntry kind="2" symbol="A01B0013100000" ipcLevel="A" entryType="K" lang="EN" nocore="yes">有另一個子ipcEntry。我可以得到<text>Means for distributing the layers on the surface</text>

我在做什麼錯在這裏?

感謝,

+1

你想要的輸出是什麼? – 2010-11-27 18:04:46

+0

基本上,打印所有的元素,以及每個元素的屬性 snoofkin 2010-11-27 18:25:55

回答

6

從XML ::嫩枝文檔:

刷新此方法不應被使用, 總是刷新樹枝,而不是元素。

purge與「齊平」 相同,但不打印樹枝。它 只是刪除目前已完全解析的所有元素。

替換清除函數,使用delete函數以相反的順序打印所有ipcEntry元素的文本,即。從最裏面的ipcEntry元素開始。

sub ipcEntrySub { 
    my ($twig_obj, $element) = @_; 

    print $element->{'att'}->{'symbol'} . "\n"; 
    print "Kind: $element->{'att'}->{'kind'}\n"; 
    print $element->text . "\n"; 

    $element->delete; 
}