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);
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.