2012-11-15 38 views
1

我需要在子元素中插入一個子元素。我有兩個孩子,第一個孩子剪切並粘貼到第二個孩子插入爲第一個孩子。如何插入子xml樹枝

XML:

<fn id="fn1_1"> 
    <label>1</label> 
    <p>The distinguished as &amp;#x2018;bisexuation.&amp;#x2019;</p> 
    </fn> 

我試圖

sub fngroup{ 
my ($xml_twig_content, $fn_group) = @_; 
@text = $fn_group->children; 
my $cut; 
foreach my $fn (@text){ 
$cut = $fn->cut if ($fn->name =~ /label/); 
if ($fn =~ /p/){ 
$fn->paste('first_child', $cut); 
} 
} 
} 

我不能處理它。我如何剪切標籤並將標籤粘貼粘貼到p標籤上作爲first_child。

我需要:

<fn id="fn1_1"> 
<p><label>1</label> The distinguished as &amp;#x2018;bisexuation.&amp;#x2019;</p> 
</fn> 

回答

3

有幾個與你的代碼的問題:第一個處理程序應適用於fn,不fngroup,那麼你正在測試$fn =~ /p/代替$fn->name =~ /p/

所以這會工作:

#!/usr/bin/perl 

use strict; 
use warnings; 

use XML::Twig; 

XML::Twig->new(twig_handlers => { fn => \&fn}) 
     ->parse(\*DATA) 
     ->print; 

sub fn { 
    my ($xml_twig_content, $fn) = @_; 
    my @text = $fn->children; 
    my $cut; 
    foreach my $fn (@text){ 
     $cut = $fn->cut if ($fn->name =~ /label/); 
     if ($fn->name =~ /p/){ 
      $cut->paste(first_child => $fn); 
     } 
    } 
} 

__DATA__ 
<foo> 
    <fngroup> 
    <fn id="fn1_1"> 
     <label>1</label> 
     <p>The distinguished as &amp;#x2018;bisexuation.&amp;#x2019;</p> 
    </fn> 
    </fngroup> 
</foo> 

這是不必要的,雖然複雜。爲什麼不能簡單地使用處理程序:

sub fn { 
    my ($twig, $fn) = @_; 
    $fn->first_child('label')->move(first_child => $fn->first_child('p')); 
} 
+0

非常感謝你,它的工作太棒了.. – user1811486