开发者

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 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->createElemen开发者_开发技巧t("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?


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);


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜