问题描述
我有一个xml文件,如下图:
I have an xml file as shown below:
<root>
<element1>abc</element1>
<element2>123</element2>
<element3>456</element3>
</root>
我正在尝试使用 xml:dom 在 perl 中添加和 element4
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);
我收到错误:"未定义的子程序 &XML::LibXML::Element::getNodeType"
I am getting the error:"Undefined subroutine &XML::LibXML::Element::getNodeType "
我尝试了 insetBefore 方法,通过查找元素并尝试在此之前插入它.
i tried insetBefore method to, by finding elements and tried to insert it before that.
任何指针,我做错了什么?
Any pointers, what am i doing wrong?
推荐答案
XML::DOM 似乎最后一次更新是在 2000 年,这意味着它不是很受支持的模块.看起来 XML::LibXML 提供了非常相似的接口,请参见下面的工作示例:
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);
这篇关于在perl中向xml文件添加和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!