2010-01-07 20 views
3

爲什麼我在輸出中獲得兩次我的字符串?XML :: Twig爲什麼輸出提取的字符串兩次?

#!/usr/bin/perl 
use warnings; 
use strict; 

use XML::Twig; 


my $string = '<cd_catalogue><title>Hello, World!</title></cd_catalogue>'; 

my $t= XML::Twig->new( twig_handlers => { cd_catalogue => \&cd_catalogue, }, 
      pretty_print => 'indented', 
); 

$t->parse($string); 


sub cd_catalogue { 
    my($t, $cd_catalogue) = @_; 
    $cd_catalogue->flush; 
} 


# Output: 
#<cd_catalogue> 
# <title>Hello, World!</title> 
#</cd_catalogue> 
#<cd_catalogue> 
# <title>Hello, World!</title> 
#</cd_catalogue> 

回答

4

改變你的子使用printpurge代替flush都繞問題:

sub cd_catalogue { 
    my($t, $cd_catalogue) = @_; 
    $cd_catalogue->print; 
    $cd_catalogue->purge; 
} 

flush,是因爲你的榜樣的簡單性越來越困惑,因爲cd_catalogue是根節點。如果你改變你的數據是這樣的:

my $string = ' 
    <cds> 
     <cd_catalogue><title>Hello, World!</title></cd_catalogue> 
    </cds>'; 

,或者如果你改變了你的twig_handler尋找title

twig_handlers => { title => \&cd_catalogue } 

,那麼你會發現,$cd_catalogue->flush現在的作品與您的預期$string

/I3az/

4

您的程序錯誤地使用了XML :: Twig。 According to the documentation,你應該「總是沖洗樹枝,而不是元素。」

變化cd_catalogue

sub cd_catalogue { 
    my($t, $cd_catalogue) = @_; 
    $t->flush; 
} 

得到預期的行爲。

+0

奇怪的是,這是我原來在我的答案:)然而,文檔確實說,也提供了使用與「元素」沖洗的例子(http://search.cpan.org/dist/XML-Twig/Twig。下午#Processing_an_XML_document_chunk_by_chunk)。 – draegtun 2010-01-07 11:10:54

+3

是的,沖洗一個元素衝到該元素,我會修復文檔。謝謝 – mirod 2010-01-10 10:13:22

相關問題