maddy
maddy

Reputation: 83

how insert an ancestor for an element

I Want to insert B1 element as a ancestor for 'C' Element. Below i have pasted my sample xml and perl code

Input

  <A>
   <B>
    <C>
     <D>name</D>
     <E>number</E>
    </C>
   </B>
  </A>

output

<A>
  <B>
   <B1></B1>
     <C>
      <D>name</D>
      <E>number</E>
     </C>
  </B>
  </A>

I Want need output like this

 <A>
  <B>
   <B1>
     <C>
      <D>name</D>
      <E>number</E>
     </C>
    <B1>
  </B>
  </A>

my code

When I run the code it inserts only the element title does not create an acestor

#!/usr/bin/perl

use strict;

use warnings;

use XML::LibXML;

my $parser = XML::LibXML->new;

my $doc = $parser->parse_file("mytest.xml");

my $root = $doc->getDocumentElement();

my ($ref_node) = $doc->findnodes('\A\B');

my $new_element= $doc->createElement("B1");

$ref_node->parentNode->insertAfter($new_element, $ref_node);

print $root->toString(1);

Upvotes: 2

Views: 73

Answers (1)

choroba
choroba

Reputation: 242103

You have to remove the inner node and insert it into the new element:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $doc         = 'XML::LibXML'->load_xml( location => 'mytest.xml' );
my $root        = $doc->getDocumentElement();
my $new_element = $doc->createElement('B1');

my ($parent) = $doc->findnodes('/A/B');
my ($inner)  = $parent->findnodes('C');

$new_element->addChild($inner);
$parent->addChild($new_element);

print $root->toString();

Or, for shorter code, using XML::XSH2:

open mytest.xml ;
wrap B1 A/B/C ;
save :b ;

Upvotes: 3

Related Questions