1

子要素に子を挿入する必要があります。私は 2 人の子を持っています。最初の子はカット アンド ペーストして 2 番目の子に最初の子として挿入します。

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);
}
}
}

処理できません。ラベルを切り取り、ラベル タグを first_child として p タグに貼り付けるにはどうすればよいですか。

私は欲しい:

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

1 に答える 1

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'));
}
于 2012-11-15T06:23:22.477 に答える