Reputation: 608
<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
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:
element
of top
, not the second.$ref_node->parentNode
, not $ref_node
.$ref_node
, not after undef
.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