使用 perl 将字符串 xml 插入到节点 [英] using perl insert string xml to a node

查看:38
本文介绍了使用 perl 将字符串 xml 插入到节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在变量 $myXML 中有以下 xml 作为字符串,需要将其插入 root->grouping

I have the following xml as a string in a variable $myXML and need to insert it inside root->grouping

<mydata seq="ee">
    <subdata name="bla" value="bla" />
</mydata>

上面的xml需要插入root->grouping

The above xml needs to be inserted inside root->grouping

<root>
  <grouping>    
  </grouping>
</root>

我目前正在使用 XML::Twig,所以如果您能帮我使用它,那么理想情况下

I am currently using XML::Twig so ideally if you could help me using that

我正在处理一个复杂的 <根 > 驻留在文件中的结构.我需要一种方法来加载 <root > xml 到 perl 并将我的 xml 字符串作为节点插入.同样在我的情况下 <分组 > 里面已经有一些节点了.

edit: I'm dealing with a complex < root > structure that resides in a file. I need a way to load that < root > xml into perl and insert my xml string as a node. Also in my case < grouping > already has some nodes inside it.

推荐答案

我会这样做:我会从 $myXML 中的 XML 创建一个元素,然后将其添加为最后一个grouping 的孩子:

This is how I would do it: I would create an element from the XML in $myXML, then add it as the last child of grouping:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $myXML='<mydata seq="ee"><subdata name="bla" value="bla" /></mydata>';

my $t= XML::Twig->new( twig_handlers => { grouping => sub { grouping( $myXML, @_); }, })
                ->parsefile( "so_insert.xml");

$t->print;
exit;

sub grouping
  { my( $xml, $t, $grouping)= @_;
    my $new_elt= XML::Twig::Elt->parse( $xml);
    $new_elt->paste( last_child => $grouping);
  }

这篇关于使用 perl 将字符串 xml 插入到节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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