add and element to xml file in perl

2019-02-25 12:55发布

问题:

I have an xml file as shown below:

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

I am trying to add and element4 in 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 am getting the error: "Undefined subroutine &XML::LibXML::Element::getNodeType "

i tried insetBefore method to, by finding elements and tried to insert it before that.

Any pointers, what am i doing wrong?

回答1:

XML::DOM seems to be last updated in 2000, which means it is not very much supported module. It looks like XML::LibXML provides very similar interface, see below 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);


回答2:

It worked fine for me, and didn't read XML::LibXML (it used XML::Parser::Expat). I have XML::DOM version 1.44 installed.

Of course, you could try installing XML::LibXML and see if that fixes the problem.



回答3:

I think the simplest 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;