user391986
user391986

Reputation: 30896

using perl insert string xml to a node

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>

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

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

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

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.

Upvotes: 3

Views: 1211

Answers (3)

mirod
mirod

Reputation: 16161

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

Upvotes: 3

unpythonic
unpythonic

Reputation: 4070

Use a twig handler to insert content upon seeing the grouping tag.

Assuming your root/grouping data is in foo.xml:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

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

my $xml = XML::Twig->new(
    pretty_print => 'indented',
    twig_handlers => {
        grouping => sub { $_->set_text($myXML)->set_asis; }
    });

$xml->parsefile("foo.xml") or die "Failed parse of foo.xml: $@\n";
$xml->print;

Upvotes: 2

Alex Howansky
Alex Howansky

Reputation: 53553

Am I missing something?

$myXML = '<root><grouping>' . $myXML . '</grouping></root>';

Upvotes: 0

Related Questions