问题
I need insert a child in child element. I have two child, the first child cut and paste to second child insert as first child.
xml:
<fn id="fn1_1">
<label>1</label>
<p>The distinguished as &#x2018;bisexuation.&#x2019;</p>
</fn>
I tried
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);
}
}
}
I can't process it. how can I cut label and the label tag paste to p tag as first_child.
I need:
<fn id="fn1_1">
<p><label>1</label> The distinguished as &#x2018;bisexuation.&#x2019;</p>
</fn>
回答1:
There is a couple of problems with your code: first the handler should be applied to fn
, not fngroup
, then you're testing $fn =~ /p/
instead of $fn->name =~ /p/
.
So this would work:
#!/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 &#x2018;bisexuation.&#x2019;</p>
</fn>
</fngroup>
</foo>
It is unnecessarily complicated though. Why not have the handler be simply:
sub fn {
my ($twig, $fn) = @_;
$fn->first_child( 'label')->move( first_child => $fn->first_child( 'p'));
}
来源:https://stackoverflow.com/questions/13392089/how-to-insert-child-xml-twig