如何插入子xml树枝 [英] how to insert child xml twig

查看:76
本文介绍了如何插入子xml树枝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在child元素中插入一个child.我有两个孩子,第一个孩子剪切并粘贴到第二个孩子中,作为第一个孩子插入.

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>

我尝试过

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_tag作为first_child.

I can't process it. how can I cut label and the label tag paste to p tag as first_child.

我需要:

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

推荐答案

您的代码有两个问题:首先应将处理程序应用于fn,而不是fngroup,然后再测试而不是$fn->name =~ /p/.

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/.

所以这可以工作:

#!/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'));
}

这篇关于如何插入子xml树枝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆