Paul
Paul

Reputation: 608

insert after child libxml perl

<root>
 <element>abc</element>
<top>
 <element>after</element>
<element>before</element>
</top>
 <element>456</element>
</root>

I want to insert another element after element and before element. Tried a few variations, must be missing something.

#!/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 @node = $doc->find('//top/element[2]');

my $new_element= $doc->createElement("element");
$new_element->appendText('testing');

$node[0]->insertAfter($new_element, undef);

print $root->toString(1);

Upvotes: 2

Views: 1137

Answers (1)

ikegami
ikegami

Reputation: 386491

$node[0] is the referenced node (i.e. the node relative to which we want to insert). Let's call it $ref_node instead.

Your code suffers from the following problems:

  • You want to insert after the first element of top, not the second.
  • You want to insert it as a child of $ref_node->parentNode, not $ref_node.
  • You want to insert it after $ref_node, not after undef.
  • You're also using find (which returns a NodeList) when you want findnodes (which returns the actual nodes).

So,

my ($ref_node) = $doc->findnodes('//top/element[1]');
$ref_node->parentNode->insertAfter($new_element, $ref_node);

Upvotes: 3

Related Questions