how to insert child xml twig

主宰稳场 提交于 2019-12-13 19:19:14

问题


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 &amp;#x2018;bisexuation.&amp;#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 &amp;#x2018;bisexuation.&amp;#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 &amp;#x2018;bisexuation.&amp;#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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!