I'm trying to add elements to XML using XML::LibXML. I know how to add elements, but I'm having a hard time trying to go to lower levels of the elements. For instance:
---- ORIGINAL FILE ----
<dict>
<key>TEST1</key>
<key>TEST2</key>
<string>en</string>
<key>TEST3</key>
</dict>
---- RESULTS I WANT ----
<dict>
<key>ADDKEY</key>
<array>
<dict>
<key>SAMPLEKEY</key>
<array>
<string>STRING</string>
</array>
</dict>
</array>
<key>TEST1</key>
<string>en</string>
<key>TEST2</key>
</dict>
I'd also like to add it before the TEST1 key. The results I get from below is that it appends it to the end of the 'dict' element.
---- WHAT I HAVE SO FAR ----
use strict;
use warnings;
use XML::LibXML;
# load
open my $fh, '<', 'test.xml';
binmode $fh; # drop all PerlIO layers possibly created by a use open
+ pragma
my $doc = XML::LibXML->load_xml(IO => $fh);
my $root=$doc->getDocumentElement();
# Grabs the 'dict' element
my $rootElement = pop(@{$root>getElementsByTagName('dict')});
my $keyElement= $doc->createElement("key");
$keyElement->appendText('Test');
$rootElement->appendChild($keyElement);
# save
open my $out, '>', 'out.xml';
binmode $out;
$doc->toFH($out);