Add and element to xml file in perl

I have an xml file as shown below:

<root>
 <element1>abc</element1>
 <element2>123</element2>
 <element3>456</element3>
</root>

I am trying to add element4 to perl using xml: dom

use XML::DOM;

#parse the file
my $parser = new XML::DOM::Parser;
my $doc = $parser->parsefile ("mytest.xml");
my $root = $doc->getDocumentElement();

my $new_element= $doc->createElement("element4");
my $new_element_text= $doc->createTextNode('testing');
$new_element->appendChild($new_element_text);

$root->appendChild($new_element);

I get an error: "Undefined routine & XML :: LibXML :: Element :: getNodeType"

I tried the insetBefore method, finding the elements and tried to insert it before that.

Any pointers what am I doing wrong?

+3
source share
3 answers

XML :: DOM is apparently the last time it was updated in 2000, which means that it is not very supported by the module. It looks like XML :: LibXML provides a very similar interface, see below a working example:

use XML::LibXML;

my $parser = XML::LibXML->new;
my $doc = $parser->parse_file("mytest.xml");
my $root = $doc->getDocumentElement();

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

$root->appendChild($new_element);

print $root->toString(1);
+6
source

XML:: LibXML ( XML:: Parser:: Expat). ​​ XML:: DOM 1.44.

, XML:: LibXML , .

0

I think the easiest way to do this is with XML :: Simple

use XML::Simple;

my $xml = XMLin('mytest.xml', ForceArray => 1);
$xml->{element4} = ['789'];
open(XML, '>mytest_out.xml');
binmode(XML, ":utf8");
print XML '<?xml version="1.0" encoding="UTF-8"?>'."\n".XMLout($xml, RootName => 'root');
close XML;
0
source

All Articles